import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import Integration from '../models/Integration.js';
import Project from '../models/Project.js';

const router = express.Router();

// Get all integrations for a project
router.get('/project/:projectId', authenticateToken, async (req, res, next) => {
  try {
    const project = await Project.findOne({
      where: { id: req.params.projectId, userId: req.user.id }
    });

    if (!project) {
      return res.status(404).json({
        status: 'error',
        code: 'PROJECT_NOT_FOUND',
        message: 'Project not found',
        data: null
      });
    }

    const integrations = await Integration.findAll({
      where: { projectId: req.params.projectId }
    });

    res.status(200).json({
      status: 'success',
      code: 'INTEGRATIONS_RETRIEVED',
      message: 'Integrations retrieved successfully',
      data: { integrations }
    });
  } catch (error) {
    next(error);
  }
});

// Create integration
router.post('/', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, type, name, config } = req.body;

    const project = await Project.findOne({
      where: { id: projectId, userId: req.user.id }
    });

    if (!project) {
      return res.status(404).json({
        status: 'error',
        code: 'PROJECT_NOT_FOUND',
        message: 'Project not found',
        data: null
      });
    }

    if (!type || !name || !config) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Type, name, and config are required',
        data: null
      });
    }

    const integration = await Integration.create({
      projectId,
      type,
      name,
      config
    });

    res.status(201).json({
      status: 'success',
      code: 'INTEGRATION_CREATED',
      message: 'Integration created successfully',
      data: { integration }
    });
  } catch (error) {
    next(error);
  }
});

// Update integration
router.put('/:id', authenticateToken, async (req, res, next) => {
  try {
    const integration = await Integration.findByPk(req.params.id);

    if (!integration) {
      return res.status(404).json({
        status: 'error',
        code: 'INTEGRATION_NOT_FOUND',
        message: 'Integration not found',
        data: null
      });
    }

    const project = await Project.findOne({
      where: { id: integration.projectId, userId: req.user.id }
    });

    if (!project) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'You do not have permission to modify this integration',
        data: null
      });
    }

    const { name, config, isActive } = req.body;

    await integration.update({
      name: name || integration.name,
      config: config || integration.config,
      isActive: isActive !== undefined ? isActive : integration.isActive
    });

    res.status(200).json({
      status: 'success',
      code: 'INTEGRATION_UPDATED',
      message: 'Integration updated successfully',
      data: { integration }
    });
  } catch (error) {
    next(error);
  }
});

// Delete integration
router.delete('/:id', authenticateToken, async (req, res, next) => {
  try {
    const integration = await Integration.findByPk(req.params.id);

    if (!integration) {
      return res.status(404).json({
        status: 'error',
        code: 'INTEGRATION_NOT_FOUND',
        message: 'Integration not found',
        data: null
      });
    }

    const project = await Project.findOne({
      where: { id: integration.projectId, userId: req.user.id }
    });

    if (!project) {
      return res.status(403).json({
        status: 'error',
        code: 'FORBIDDEN',
        message: 'You do not have permission to modify this integration',
        data: null
      });
    }

    await integration.destroy();

    res.status(200).json({
      status: 'success',
      code: 'INTEGRATION_DELETED',
      message: 'Integration deleted successfully',
      data: null
    });
  } catch (error) {
    next(error);
  }
});

export default router;
