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

const router = express.Router();

// Get all tokens 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 { category } = req.query;
    const where = { projectId: req.params.projectId };
    if (category) {
      where.category = category;
    }

    const tokens = await Token.findAll({ where });

    res.status(200).json({
      status: 'success',
      code: 'TOKENS_RETRIEVED',
      message: 'Tokens retrieved successfully',
      data: { tokens }
    });
  } catch (error) {
    next(error);
  }
});

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

    const token = await Token.create({
      projectId,
      name,
      category,
      value,
      description,
      source: 'manual'
    });

    res.status(201).json({
      status: 'success',
      code: 'TOKEN_CREATED',
      message: 'Token created successfully',
      data: { token }
    });
  } catch (error) {
    next(error);
  }
});

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

    if (!token) {
      return res.status(404).json({
        status: 'error',
        code: 'TOKEN_NOT_FOUND',
        message: 'Token not found',
        data: null
      });
    }

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

    const { name, category, value, description } = req.body;

    await token.update({
      name: name || token.name,
      category: category || token.category,
      value: value || token.value,
      description: description !== undefined ? description : token.description
    });

    res.status(200).json({
      status: 'success',
      code: 'TOKEN_UPDATED',
      message: 'Token updated successfully',
      data: { token }
    });
  } catch (error) {
    next(error);
  }
});

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

    if (!token) {
      return res.status(404).json({
        status: 'error',
        code: 'TOKEN_NOT_FOUND',
        message: 'Token not found',
        data: null
      });
    }

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

    await token.destroy();

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

export default router;
