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

const router = express.Router();

// Get all components 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 components = await Component.findAll({
      where: { projectId: req.params.projectId },
      order: [['createdAt', 'DESC']]
    });

    res.status(200).json({
      status: 'success',
      code: 'COMPONENTS_RETRIEVED',
      message: 'Components retrieved successfully',
      data: { components }
    });
  } catch (error) {
    next(error);
  }
});

// Create component
router.post('/', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, name, description, category, figmaId, storybookPath } = 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 (!name) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Name is required',
        data: null
      });
    }

    const component = await Component.create({
      projectId,
      name,
      description,
      category,
      figmaId,
      storybookPath
    });

    res.status(201).json({
      status: 'success',
      code: 'COMPONENT_CREATED',
      message: 'Component created successfully',
      data: { component }
    });
  } catch (error) {
    next(error);
  }
});

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

    if (!component) {
      return res.status(404).json({
        status: 'error',
        code: 'COMPONENT_NOT_FOUND',
        message: 'Component not found',
        data: null
      });
    }

    const project = await Project.findOne({
      where: { id: component.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 component',
        data: null
      });
    }

    const { name, description, category, status, adoptionScore, variants } = req.body;

    await component.update({
      name: name || component.name,
      description: description !== undefined ? description : component.description,
      category: category || component.category,
      status: status || component.status,
      adoptionScore: adoptionScore !== undefined ? adoptionScore : component.adoptionScore,
      variants: variants || component.variants
    });

    res.status(200).json({
      status: 'success',
      code: 'COMPONENT_UPDATED',
      message: 'Component updated successfully',
      data: { component }
    });
  } catch (error) {
    next(error);
  }
});

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

    if (!component) {
      return res.status(404).json({
        status: 'error',
        code: 'COMPONENT_NOT_FOUND',
        message: 'Component not found',
        data: null
      });
    }

    const project = await Project.findOne({
      where: { id: component.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 component',
        data: null
      });
    }

    await component.destroy();

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

export default router;
