/**
 * SEO Controller
 * Handles HTTP requests for SEO landing pages
 */

const seoService = require('../services/seo.service');
const ErrorHandler = require('../utils/ErrorHandler');
const { catchAsyncErrors } = require('../middlewares/catchAsyncErrors');

// ==========================================
// PUBLIC ENDPOINTS (No Auth Required)
// ==========================================

// GET /api/v1/seo/intercity-routes
exports.getIntercityRoutes = catchAsyncErrors(async (req, res, next) => {
    try {
        const { search, page, limit } = req.query;
        const result = await seoService.getIntercityRoutes(
            { isActive: true, search },
            { page, limit }
        );
        res.status(200).json({ success: true, ...result });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// GET /api/v1/seo/intercity-routes/:slug
exports.getIntercityRouteBySlug = catchAsyncErrors(async (req, res, next) => {
    try {
        const { slug } = req.params;  // slug comes from URL path, not query
        const { isActive } = req.query;  // isActive is optional query param

        const route = await seoService.getIntercityRouteBySlug(slug, isActive);
        res.status(200).json({ success: true, data: route });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// GET /api/v1/seo/airport-routes
exports.getAirportRoutes = catchAsyncErrors(async (req, res, next) => {
    try {
        const { search, routeType, page, limit } = req.query;
        const result = await seoService.getAirportRoutes(
            { isActive: true, routeType, search },
            { page, limit }
        );
        // console.log("result", result)
        res.status(200).json({ success: true, ...result });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// GET /api/v1/seo/airport-routes/:slug
exports.getAirportRouteBySlug = catchAsyncErrors(async (req, res, next) => {
    try {
        const route = await seoService.getAirportRouteBySlug(req.params.slug);
        res.status(200).json({ success: true, data: route });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// GET /api/v1/seo/city-services
exports.getCityTaxiServices = catchAsyncErrors(async (req, res, next) => {
    try {
        const { search, page, limit } = req.query;
        const result = await seoService.getCityTaxiServices(
            { isActive: true, search },
            { page, limit }
        );
        res.status(200).json({ success: true, ...result });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// GET /api/v1/seo/city-services/:slug
exports.getCityTaxiServiceBySlug = catchAsyncErrors(async (req, res, next) => {
    try {
        const service = await seoService.getCityTaxiServiceBySlug(req.params.slug);
        res.status(200).json({ success: true, data: service });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// ==========================================
// ADMIN ENDPOINTS (Authenticated, Super-Admin)
// ==========================================

// GET /api/v1/seo/admin/overview
exports.getAdminOverview = catchAsyncErrors(async (req, res, next) => {
    try {
        const overview = await seoService.getAdminOverview();
        res.status(200).json({ success: true, data: overview });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// --- INTERCITY ROUTES ADMIN ---

// GET /api/v1/seo/admin/intercity-routes (with inactive)
exports.getAdminIntercityRoutes = catchAsyncErrors(async (req, res, next) => {
    try {
        const { search, isActive, page, limit } = req.query;
        const result = await seoService.getIntercityRoutes(
            { isActive: isActive === 'false' ? false : (isActive === 'true' ? true : undefined), search },
            { page, limit }
        );
        res.status(200).json({ success: true, ...result });
    } catch (err) {
        console.log(err)
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// POST /api/v1/seo/admin/intercity-routes
exports.createIntercityRoute = catchAsyncErrors(async (req, res, next) => {
    try {
        const route = await seoService.createIntercityRoute(req.body, req.user._id);
        res.status(201).json({ success: true, message: 'Intercity route created successfully', data: route });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// PUT /api/v1/seo/admin/intercity-routes/:id
exports.updateIntercityRoute = catchAsyncErrors(async (req, res, next) => {
    try {
        const route = await seoService.updateIntercityRoute(req.params.id, req.body);
        res.status(200).json({ success: true, message: 'Intercity route updated successfully', data: route });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// DELETE /api/v1/seo/admin/intercity-routes/:id
exports.deleteIntercityRoute = catchAsyncErrors(async (req, res, next) => {
    try {
        await seoService.deleteIntercityRoute(req.params.id);
        res.status(200).json({ success: true, message: 'Intercity route deleted successfully' });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// --- AIRPORT ROUTES ADMIN ---

// GET /api/v1/seo/admin/airport-routes
exports.getAdminAirportRoutes = catchAsyncErrors(async (req, res, next) => {
    try {
        const { search, routeType, isActive, page, limit } = req.query;
        const result = await seoService.getAirportRoutes(
            { isActive: isActive === 'false' ? false : (isActive === 'true' ? true : undefined), routeType, search },
            { page, limit }
        );
        res.status(200).json({ success: true, ...result });
    } catch (err) {
        console.log(err)
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// POST /api/v1/seo/admin/airport-routes
exports.createAirportRoute = catchAsyncErrors(async (req, res, next) => {
    try {
        const route = await seoService.createAirportRoute(req.body, req.user._id);
        res.status(201).json({ success: true, message: 'Airport route created successfully', data: route });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// PUT /api/v1/seo/admin/airport-routes/:id
exports.updateAirportRoute = catchAsyncErrors(async (req, res, next) => {
    try {
        const route = await seoService.updateAirportRoute(req.params.id, req.body);
        res.status(200).json({ success: true, message: 'Airport route updated successfully', data: route });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// DELETE /api/v1/seo/admin/airport-routes/:id
exports.deleteAirportRoute = catchAsyncErrors(async (req, res, next) => {
    try {
        await seoService.deleteAirportRoute(req.params.id);
        res.status(200).json({ success: true, message: 'Airport route deleted successfully' });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// --- CITY TAXI SERVICES ADMIN ---

// GET /api/v1/seo/admin/city-services
exports.getAdminCityTaxiServices = catchAsyncErrors(async (req, res, next) => {
    try {
        const { search, isActive, page, limit } = req.query;
        const result = await seoService.getCityTaxiServices(
            { isActive: isActive === 'false' ? false : (isActive === 'true' ? true : undefined), search },
            { page, limit }
        );
        res.status(200).json({ success: true, ...result });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// POST /api/v1/seo/admin/city-services
exports.createCityTaxiService = catchAsyncErrors(async (req, res, next) => {
    try {
        const service = await seoService.createCityTaxiService(req.body, req.user._id);
        res.status(201).json({ success: true, message: 'City taxi service created successfully', data: service });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// PUT /api/v1/seo/admin/city-services/:id
exports.updateCityTaxiService = catchAsyncErrors(async (req, res, next) => {
    try {
        const service = await seoService.updateCityTaxiService(req.params.id, req.body);
        res.status(200).json({ success: true, message: 'City taxi service updated successfully', data: service });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// DELETE /api/v1/seo/admin/city-services/:id
exports.deleteCityTaxiService = catchAsyncErrors(async (req, res, next) => {
    try {
        await seoService.deleteCityTaxiService(req.params.id);
        res.status(200).json({ success: true, message: 'City taxi service deleted successfully' });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

// TOGGLE STATUS (works for all types)
// PATCH /api/v1/seo/admin/toggle-status/:type/:id
exports.toggleActiveStatus = catchAsyncErrors(async (req, res, next) => {
    try {
        const { type, id } = req.params;
        const entity = await seoService.toggleActiveStatus(type, id);
        res.status(200).json({
            success: true,
            message: `Status toggled to ${entity.isActive ? 'active' : 'inactive'}`,
            data: entity
        });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

/**
 * Real-time cab search for Intercity SEO route
 * GET /api/v1/seo/search/intercity/:slug
 */
exports.searchIntercityCabs = catchAsyncErrors(async (req, res, next) => {
    try {
        const { slug } = req.params;
        const result = await seoService.searchIntercityCabs(slug, req.query);

        res.status(200).json({
            success: true,
            data: result
        });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

/**
 * Real-time cab search for Airport SEO route
 * GET /api/v1/seo/search/airport/:slug
 */
exports.searchAirportCabs = catchAsyncErrors(async (req, res, next) => {
    try {
        const { slug } = req.params;
        const result = await seoService.searchAirportCabs(slug, req.query);
        // console.log("result", result)

        res.status(200).json({
            success: true,
            data: result
        });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});

/**
 * Real-time cab search for City Taxi SEO route
 * GET /api/v1/seo/search/city/:slug
 */
exports.searchCityCabs = catchAsyncErrors(async (req, res, next) => {
    try {
        const { slug } = req.params;
        const result = await seoService.searchCityCabs(slug, req.query);
        console.log("result", result)

        res.status(200).json({
            success: true,
            data: result
        });
    } catch (err) {
        return next(new ErrorHandler(err.message, err.statusCode || 500));
    }
});


