import { NextApiResponse } from 'next';
import { AuthenticatedRequest } from '../../../../lib/middleware/authMiddleware';
import { requireAdmin } from '../../../../lib/middleware/adminMiddleware';
import { getServerConfig, setServerConfig } from '../../../../lib/serverConfig';
import { resetPrisma } from '../../../../lib/prisma';

const SYSTEM_CONFIG = {
    maintenanceMode: false,
    apiVersion: '1.0.0',
    maxUploadMB: getServerConfig().uploadMaxMB,
    dbHost: getServerConfig().dbHost,
    dbPort: getServerConfig().dbPort,
    dbUser: getServerConfig().dbUser,
    dbPass: getServerConfig().dbPass,
    dbName: getServerConfig().dbName,
    uploadDir: getServerConfig().uploadDir,
};

export default async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
    // Require admin authentication
    const isAdmin = await requireAdmin(req, res);
    if (!isAdmin) {
        return;
    }

    if (req.method === 'GET') {
        // Return non-sensitive system configuration
        return res.status(200).json({
            success: true,
            data: SYSTEM_CONFIG
        });
    }

    if (req.method === 'PUT') {
        const body = req.body || {};
        const before = getServerConfig();
        const nextCfg = setServerConfig({
            uploadMaxMB: body.maxUploadMB,
            uploadDir: body.uploadDir,
            dbHost: body.dbHost,
            dbPort: body.dbPort,
            dbUser: body.dbUser,
            dbPass: body.dbPass,
            dbName: body.dbName,
        });
        SYSTEM_CONFIG.maxUploadMB = nextCfg.uploadMaxMB;
        SYSTEM_CONFIG.uploadDir = nextCfg.uploadDir;
        SYSTEM_CONFIG.dbHost = nextCfg.dbHost;
        SYSTEM_CONFIG.dbPort = nextCfg.dbPort;
        SYSTEM_CONFIG.dbUser = nextCfg.dbUser;
        SYSTEM_CONFIG.dbPass = nextCfg.dbPass;
        SYSTEM_CONFIG.dbName = nextCfg.dbName;
        const dbChanged = before.dbHost !== nextCfg.dbHost || before.dbPort !== nextCfg.dbPort || before.dbUser !== nextCfg.dbUser || before.dbPass !== nextCfg.dbPass || before.dbName !== nextCfg.dbName;
        if (dbChanged) {
            resetPrisma();
        }
        return res.status(200).json({ success: true, message: 'Configuration updated successfully', data: SYSTEM_CONFIG });
    }

    return res.status(405).json({ success: false, error: 'Method not allowed' });
}
