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

const router = express.Router();

/**
 * PHASE 5A: Figma Integration Endpoints
 * 9 endpoints for complete Figma design system integration
 */

// 1. GET /api/figma/health - Check Figma API connectivity
router.get('/health', authenticateToken, async (req, res, next) => {
  try {
    // Mock Figma API health check
    const figmaHealth = {
      status: 'healthy',
      apiVersion: '2.0',
      lastCheck: new Date().toISOString(),
      responseTime: Math.floor(Math.random() * 100) + 50
    };

    res.status(200).json({
      status: 'success',
      code: 'FIGMA_HEALTH_OK',
      message: 'Figma API is healthy',
      data: figmaHealth
    });
  } catch (error) {
    next(error);
  }
});

// 2. POST /api/figma/extract-variables - Extract Figma variables
router.post('/extract-variables', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'extract-variables',
      status: 'queued'
    });

    console.log(`[Figma] Extract variables queued: ${sync.id}`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_EXTRACTION_STARTED',
      message: 'Variable extraction started',
      data: {
        syncId: sync.id,
        status: 'queued',
        estimatedTime: '1-2 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 3. POST /api/figma/extract-components - Extract component library
router.post('/extract-components', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'extract-components',
      status: 'queued'
    });

    console.log(`[Figma] Extract components queued: ${sync.id}`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_COMPONENT_EXTRACTION_STARTED',
      message: 'Component extraction started',
      data: {
        syncId: sync.id,
        status: 'queued',
        estimatedTime: '3-5 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 4. POST /api/figma/extract-styles - Extract design tokens/styles
router.post('/extract-styles', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'extract-styles',
      status: 'queued'
    });

    console.log(`[Figma] Extract styles queued: ${sync.id}`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_STYLE_EXTRACTION_STARTED',
      message: 'Style extraction started',
      data: {
        syncId: sync.id,
        status: 'queued',
        estimatedTime: '2-3 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 5. POST /api/figma/sync-tokens - Sync tokens bidirectionally
router.post('/sync-tokens', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'sync-tokens',
      status: 'queued'
    });

    console.log(`[Figma] Token sync queued: ${sync.id}`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_TOKEN_SYNC_STARTED',
      message: 'Token synchronization started',
      data: {
        syncId: sync.id,
        status: 'queued',
        estimatedTime: '2-4 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 6. POST /api/figma/visual-diff - Compare Figma vs codebase
router.post('/visual-diff', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'visual-diff',
      status: 'queued'
    });

    console.log(`[Figma] Visual diff queued: ${sync.id}`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_DIFF_STARTED',
      message: 'Visual diff comparison started',
      data: {
        syncId: sync.id,
        status: 'queued',
        estimatedTime: '3-5 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 7. POST /api/figma/validate-components - Validate component compliance
router.post('/validate-components', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'validate-components',
      status: 'queued'
    });

    console.log(`[Figma] Component validation queued: ${sync.id}`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_VALIDATION_STARTED',
      message: 'Component validation started',
      data: {
        syncId: sync.id,
        status: 'queued',
        estimatedTime: '2-3 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 8. POST /api/figma/generate-code - Generate component code from Figma
router.post('/generate-code', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl, language = 'jsx' } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'generate-code',
      status: 'queued',
      metadata: { language }
    });

    console.log(`[Figma] Code generation queued: ${sync.id} (${language})`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_CODE_GENERATION_STARTED',
      message: 'Code generation started',
      data: {
        syncId: sync.id,
        status: 'queued',
        language,
        estimatedTime: '5-10 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 9. POST /api/figma/export-assets - Export design assets
router.post('/export-assets', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, figmaFileKey, figmaFileUrl, assetTypes = ['svg', 'png'] } = req.body;

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

    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
      });
    }

    const sync = await FigmaSync.create({
      projectId,
      userId: req.user.id,
      figmaFileKey,
      figmaFileUrl: figmaFileUrl || `https://www.figma.com/file/${figmaFileKey}`,
      syncType: 'export-assets',
      status: 'queued',
      metadata: { assetTypes }
    });

    console.log(`[Figma] Asset export queued: ${sync.id} (${assetTypes.join(',')})`);

    res.status(202).json({
      status: 'success',
      code: 'FIGMA_ASSET_EXPORT_STARTED',
      message: 'Asset export started',
      data: {
        syncId: sync.id,
        status: 'queued',
        assetTypes,
        estimatedTime: '5-15 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

export default router;
