/**
 * VerifyIndia API - Main Server Entry Point
 */

require('dotenv').config();

const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');

const { connectDB } = require('./database/connection');
const { connectRedis } = require('./cache/redis');

// Routes
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const ifscRoutes = require('./routes/ifsc');
const pincodeRoutes = require('./routes/pincode');
const gstRoutes = require('./routes/gst');
const panRoutes = require('./routes/pan');
const bankRoutes = require('./routes/bank');

const { errorHandler } = require('./middleware/errorHandler');

const app = express();

// Middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(morgan('combined'));

// Health check route
app.get('/health', (req, res) => {
    res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});

// API info route
app.get('/', (req, res) => {
    res.json({
        message: 'VerifyIndia API',
        version: 'v1',
        endpoints: {
            auth: {
                signup: 'POST /v1/auth/signup',
                login: 'POST /v1/auth/login'
            },
            user: {
                usage: 'GET /v1/user/usage',
                profile: 'GET /v1/user/profile',
                apiKeys: 'GET /v1/user/api-keys'
            },
            verification: {
                ifsc: 'GET /v1/ifsc/:ifsc_code',
                pincode: 'GET /v1/pincode/:pincode',
                gst: 'GET /v1/gst/verify/:gstin',
                pan: 'POST /v1/pan/verify',
                bank: 'POST /v1/bank/verify'
            }
        }
    });
});

// API Routes
app.use('/v1/auth', authRoutes);
app.use('/v1/user', userRoutes);
app.use('/v1/ifsc', ifscRoutes);
app.use('/v1/pincode', pincodeRoutes);
app.use('/v1/gst', gstRoutes);
app.use('/v1/pan', panRoutes);
app.use('/v1/bank', bankRoutes);

// 404 handler
app.use('*', (req, res) => {
    res.status(404).json({
        success: false,
        error: { code: 'NOT_FOUND', message: `Route ${req.originalUrl} not found` }
    });
});

// Error handler
app.use(errorHandler);

const PORT = process.env.PORT || 3000;

async function startServer() {
    try {
        await connectDB();
        console.log('✅ PostgreSQL connected');

        await connectRedis();
        console.log('✅ Redis connected');

        app.listen(PORT, () => {
            console.log(`
\x1b[36m
__      __        _  __      _           _ _       
\\ \\    / /       (_)/ _|    (_)         | (_)      
 \\ \\  / /__ _ __  _| |_ _   _ _ __   __| |_  __ _ 
  \\ \\/ / _ \ '__|| |  _| | | | '_ \\ / _\` | |/ _\` |
   \\  /  __/ |   | | | | |_| | | | | (_| | | (_| |
    \\/ \\___|_|   |_|_|  \\__, |_| |_|\\__,_|_|\\__,_|
                         __/ |                      
                        |___/                       
\x1b[0m`);
            console.log(`✅ Server running on port ${PORT}`);
            console.log(`📍 API Key Prefix: ${process.env.API_KEY_PREFIX || 'vi_'}`);
            console.log('');
            console.log('🚀 All API endpoints active:');
            console.log('   • POST /v1/auth/signup');
            console.log('   • POST /v1/auth/login');
            console.log('   • GET  /v1/user/usage');
            console.log('   • GET  /v1/ifsc/:ifsc_code');
            console.log('   • GET  /v1/pincode/:pincode');
            console.log('   • GET  /v1/gst/verify/:gstin');
            console.log('   • POST /v1/pan/verify');
            console.log('   • POST /v1/bank/verify');
        });
    } catch (error) {
        console.error('❌ Failed to start:', error);
        process.exit(1);
    }
}

startServer();
