import express from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import swaggerUi from 'swagger-ui-express';
import swaggerJsdoc from 'swagger-jsdoc';
import cors from 'cors'; 

const app = express();

const port = process.env.PORT || 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.use(cors({ origin: '*', methods: ['GET', 'POST', 'PUT', 'DELETE'] })); 

app.use(express.json());


const loadRoutes = (dir, prefix = '') => {
  fs.readdirSync(dir).forEach(async (file) => {
    const fullPath = path.join(dir, file);
    const stat = fs.statSync(fullPath);

    if (stat.isDirectory()) {
      loadRoutes(fullPath, `${prefix}/${file}`);
    } else if (file.endsWith('.js')) {
      const routeName = path.basename(file, '.js');
      try {
        const routerModule = await import(fullPath);
        const router = routerModule.default;
        
        app.use(`${prefix}/${routeName}`, router); 
        console.log(`✅ Router dimuat: ${prefix}/${routeName}`);
      } catch (err) {
        console.error(`❌ Gagal memuat router ${fullPath}:`, err.message);
      }
    }
  });
};

loadRoutes(path.join(__dirname, 'routes'));

const swaggerDefinition = {
  openapi: '3.0.0',
  info: {
    title: '📚 API APe',
    version: '1.0.0',
    description: `
Ini hanya base rest api , endpoint hanya contoh dsn masih sedikit , bisa kamu tambahkan sendiri 

Channel WA:  

📢 [🌱 AP update](https://whatsapp.com/channel/0029VaalShkGZNCsXgFPO80A)
    `,
  },
  tags: [
    { name: 'AI', description: 'Layanan kecerdasan buatan' },
    { name: 'Downloader', description: 'Layanan pengunduhan konten' },
    { name: 'Tools', description: 'Berbagai alat bantu dan utilitas' },
    { name: 'Search', description: 'Fungsi pencarian' },
  ],
 
  servers: [{ url: 'https://demo-rest-api.vercel.app' }], 
};

const swaggerSpec = swaggerJsdoc({
  definition: swaggerDefinition,
  apis: [path.join(__dirname, 'routes/**/*.js')],
});


const swaggerUiOptions = {
  customSiteTitle: "Docs API APe",

  customCssUrl: "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui.min.css",
  customJs: [
    "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-bundle.js",
    "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.15.5/swagger-ui-standalone-preset.js",
  ],

  customCss: `
    body {
      background: #fafafa !important;
      font-family: 'Roboto', sans-serif !important;
      color: #000 !important;
    }
    .swagger-ui .topbar { display: none !important; }
    .swagger-ui .info {
      background: #ffffff !important;
      border-radius: 14px;
      padding: 20px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      margin-bottom: 25px;
      color: #000 !important;
      transition: all 0.3s ease;
    }
    
    .swagger-ui .info:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(0,0,0,0.12);
    }
    .swagger-ui .info p,
    .swagger-ui .info h2,
    .swagger-ui .info h3,
    .swagger-ui .info li {
      color: #000 !important;
    }
    .swagger-ui .info a {
      color: #007bff !important;
      text-decoration: none;
      font-weight: 500;
    }
    .swagger-ui .info a:hover {
      text-decoration: underline;
    }
    .swagger-ui .opblock {
      border-radius: 12px !important;
      background: #fff !important;
      box-shadow: 0 3px 8px rgba(0,0,0,0.08);
      margin-bottom: 14px;
      transition: all 0.2s ease-in-out;
    }
    .swagger-ui .opblock:hover {
      transform: translateY(-3px);
      box-shadow: 0 6px 14px rgba(0,0,0,0.12);
    }
    .swagger-ui .wrapper {
      max-width: 960px;
      margin: 0 auto;
      padding: 20px;
    }
    @media (max-width: 768px) {
      .swagger-ui .wrapper {
        padding: 10px;
      }
      .swagger-ui .info,
      .swagger-ui .opblock {
        border-radius: 10px;
      }
    }
  `
};

app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, swaggerUiOptions));

const publicPath = path.join(__dirname, 'public'); 
app.use(express.static(publicPath));
app.get('/', (req, res) => {
    res.sendFile(path.join(publicPath, 'index.html'));
});

app.listen(port, () =>
  console.log(`🚀 Server jalan di http://localhost:${port}. Buka http://localhost:${port}/docs untuk dokumentasi API.`)
);