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

const router = express.Router();

// 1. POST /api/qa/screenshot-compare - Visual regression testing
router.post('/screenshot-compare', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, baselinePath, currentPath } = req.body;

    if (!projectId || !baselinePath || !currentPath) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'projectId, baselinePath, and currentPath 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 qaTest = await QATest.create({
      projectId,
      userId: req.user.id,
      testType: 'screenshot-compare',
      status: 'queued',
      baselineScreenshots: {
        path: baselinePath,
        count: 0,
        uploadedAt: new Date().toISOString()
      },
      currentScreenshots: {
        path: currentPath,
        count: 0,
        uploadedAt: new Date().toISOString()
      },
      metadata: {
        comparisonMode: 'pixel-perfect',
        threshold: 0.01,
        ignoreAntialiasing: false
      }
    });

    console.log(`[QA] Screenshot comparison queued: ${qaTest.id}`);

    res.status(202).json({
      status: 'success',
      code: 'SCREENSHOT_COMPARISON_STARTED',
      message: 'Screenshot comparison started',
      data: {
        testId: qaTest.id,
        status: 'queued',
        estimatedTime: '2-5 minutes'
      }
    });
  } catch (error) {
    next(error);
  }
});

// 2. POST /api/test/run - Execute test suite
router.post('/run', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, testSuite, filters } = req.body;

    if (!projectId || !testSuite) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'projectId and testSuite 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
      });
    }

    // Validate testSuite format
    const validSuites = [
      'unit',
      'integration',
      'e2e',
      'component',
      'accessibility',
      'performance'
    ];

    if (!validSuites.includes(testSuite.toLowerCase())) {
      return res.status(400).json({
        status: 'error',
        code: 'INVALID_TEST_SUITE',
        message: `Test suite must be one of: ${validSuites.join(', ')}`,
        data: null
      });
    }

    const qaTest = await QATest.create({
      projectId,
      userId: req.user.id,
      testType: 'test-run',
      status: 'queued',
      testSuite: testSuite.toLowerCase(),
      passedTests: 0,
      failedTests: 0,
      skippedTests: 0,
      metadata: {
        filters: filters || {},
        environment: process.env.NODE_ENV || 'development',
        runner: 'jest',
        parallel: true
      }
    });

    console.log(`[QA] Test run queued: ${qaTest.id} (${testSuite})`);

    res.status(202).json({
      status: 'success',
      code: 'TEST_RUN_STARTED',
      message: 'Test suite execution started',
      data: {
        testId: qaTest.id,
        status: 'queued',
        testSuite: testSuite.toLowerCase(),
        estimatedTime: '1-10 minutes depending on suite'
      }
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/qa/:id - Get QA test status and results
router.get('/:id', authenticateToken, async (req, res, next) => {
  try {
    const qaTest = await QATest.findOne({
      where: { id: req.params.id, userId: req.user.id }
    });

    if (!qaTest) {
      return res.status(404).json({
        status: 'error',
        code: 'TEST_NOT_FOUND',
        message: 'QA test not found',
        data: null
      });
    }

    res.status(200).json({
      status: 'success',
      code: 'TEST_RETRIEVED',
      message: 'QA test retrieved successfully',
      data: {
        test: {
          id: qaTest.id,
          testType: qaTest.testType,
          status: qaTest.status,
          testSuite: qaTest.testSuite,
          passedTests: qaTest.passedTests,
          failedTests: qaTest.failedTests,
          skippedTests: qaTest.skippedTests,
          totalDuration: qaTest.totalDuration,
          diffPercentage: qaTest.diffPercentage,
          error: qaTest.error,
          completedAt: qaTest.completedAt,
          createdAt: qaTest.createdAt
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

// GET /api/qa/project/:projectId - List QA tests for a project
router.get('/project/:projectId/list', authenticateToken, async (req, res, next) => {
  try {
    const { limit = 20, offset = 0 } = req.query;

    const maxLimit = 100;
    const queryLimit = Math.min(parseInt(limit) || 20, maxLimit);
    const queryOffset = parseInt(offset) || 0;

    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 { count, rows } = await QATest.findAndCountAll({
      where: { projectId: req.params.projectId },
      limit: queryLimit,
      offset: queryOffset,
      order: [['createdAt', 'DESC']]
    });

    res.status(200).json({
      status: 'success',
      code: 'QA_TESTS_RETRIEVED',
      message: 'QA tests retrieved successfully',
      data: {
        tests: rows.map(test => ({
          id: test.id,
          testType: test.testType,
          status: test.status,
          testSuite: test.testSuite,
          passedTests: test.passedTests,
          failedTests: test.failedTests,
          createdAt: test.createdAt
        })),
        pagination: {
          total: count,
          limit: queryLimit,
          offset: queryOffset
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

export default router;
