const express = require('express');
const router = express.Router();
const { 
  getAllDomains, 
  updateApiMapping, 
  validateApiServer,
  getApiServerByDomain,
  getEnvironmentInfo 
} = require('../../utils/apiMappingService');

// GET /api/mapping/domains - Lấy tất cả domains
router.get('/domains', (req, res) => {
  try {
    const domains = getAllDomains();
    res.json({
      success: true,
      data: domains
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// GET /api/mapping/domain/:domain - Lấy thông tin domain cụ thể
router.get('/domain/:domain', (req, res) => {
  try {
    const { domain } = req.params;
    const envInfo = getEnvironmentInfo(domain);
    const apiServer = getApiServerByDomain(domain);
    
    res.json({
      success: true,
      data: {
        domain: domain,
        api_server: apiServer,
        environment: envInfo?.environment || 'unknown',
        description: envInfo?.description || 'Unknown environment'
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// POST /api/mapping/add - Thêm domain mapping mới
router.post('/add', (req, res) => {
  try {
    const { domain, api_server, environment, description } = req.body;
    
    if (!domain || !api_server) {
      return res.status(400).json({
        success: false,
        error: 'Domain và API server là bắt buộc'
      });
    }
    
    const newMapping = {
      [domain]: {
        api_server: api_server,
        environment: environment || 'production',
        description: description || `KTHC ${domain}`
      }
    };
    
    const success = updateApiMapping(newMapping);
    
    if (success) {
      res.json({
        success: true,
        message: `Đã thêm mapping cho domain: ${domain}`,
        data: newMapping[domain]
      });
    } else {
      res.status(500).json({
        success: false,
        error: 'Không thể cập nhật mapping'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// PUT /api/mapping/update/:domain - Cập nhật domain mapping
router.put('/update/:domain', (req, res) => {
  try {
    const { domain } = req.params;
    const { api_server, environment, description } = req.body;
    
    if (!api_server) {
      return res.status(400).json({
        success: false,
        error: 'API server là bắt buộc'
      });
    }
    
    const updateMapping = {
      [domain]: {
        api_server: api_server,
        environment: environment || 'production',
        description: description || `KTHC ${domain}`
      }
    };
    
    const success = updateApiMapping(updateMapping);
    
    if (success) {
      res.json({
        success: true,
        message: `Đã cập nhật mapping cho domain: ${domain}`,
        data: updateMapping[domain]
      });
    } else {
      res.status(500).json({
        success: false,
        error: 'Không thể cập nhật mapping'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// DELETE /api/mapping/remove/:domain - Xóa domain mapping
router.delete('/remove/:domain', (req, res) => {
  try {
    const { domain } = req.params;
    
    // Load current mapping
    const { loadApiMapping } = require('../../utils/apiMappingService');
    const mapping = loadApiMapping();
    
    if (!mapping || !mapping.api_mapping[domain]) {
      return res.status(404).json({
        success: false,
        error: `Không tìm thấy mapping cho domain: ${domain}`
      });
    }
    
    // Remove domain from mapping
    delete mapping.api_mapping[domain];
    
    // Save updated mapping
    const fs = require('fs');
    const path = require('path');
    const mappingPath = path.join(__dirname, '../../config/api-mapping.json');
    fs.writeFileSync(mappingPath, JSON.stringify(mapping, null, 2));
    
    res.json({
      success: true,
      message: `Đã xóa mapping cho domain: ${domain}`
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// POST /api/mapping/validate - Validate API server
router.post('/validate', async (req, res) => {
  try {
    const { api_server } = req.body;
    
    if (!api_server) {
      return res.status(400).json({
        success: false,
        error: 'API server là bắt buộc'
      });
    }
    
    const validation = await validateApiServer(api_server);
    
    res.json({
      success: true,
      data: {
        api_server: api_server,
        validation: validation
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// GET /api/mapping/current - Lấy mapping hiện tại
router.get('/current', (req, res) => {
  try {
    const origin = req.headers.origin || req.headers.host;
    const domain = origin ? new URL(origin).hostname : req.headers.host;
    
    const envInfo = getEnvironmentInfo(domain);
    const apiServer = getApiServerByDomain(domain);
    
    res.json({
      success: true,
      data: {
        current_domain: domain,
        api_server: apiServer,
        environment: envInfo?.environment || 'unknown',
        description: envInfo?.description || 'Unknown environment',
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = router;
