import { Router, Request, Response } from 'express';
import { ScrapeRequest } from '../types';
import { createJob, getJob, getJobLeads } from '../engine/queue';
import { isDailyLimitReached, getRemainingToday } from '../engine/anti-detection';

const router = Router();

/**
 * POST /api/scrape — Start a new scrape job
 * Body: { searchConfig, outputConfig, maxProperties?, searchId? }
 */
router.post('/', (req: Request, res: Response) => {
  const body = req.body as ScrapeRequest;

  // Validate required fields
  if (!body.searchConfig || !body.searchConfig.location) {
    if (!body.searchId) {
      return res.status(400).json({
        error: 'searchConfig.location is required (or provide searchId for an existing search)',
      });
    }
  }

  if (!body.outputConfig) {
    return res.status(400).json({ error: 'outputConfig is required' });
  }

  // Check daily limit
  if (isDailyLimitReached()) {
    return res.status(429).json({
      error: 'Daily scraping limit reached',
      remaining: getRemainingToday(),
    });
  }

  const maxProperties = body.maxProperties || 20;

  const job = createJob(
    body.searchConfig,
    body.outputConfig,
    maxProperties,
    body.searchId
  );

  return res.status(201).json({
    jobId: job.id,
    status: job.status,
    message: `Job created. Processing up to ${maxProperties} properties.`,
  });
});

/**
 * GET /api/scrape/:id — Get job status
 */
router.get('/:id', (req: Request, res: Response) => {
  const job = getJob(req.params.id as string);
  if (!job) {
    return res.status(404).json({ error: 'Job not found' });
  }
  return res.json({ job });
});

/**
 * GET /api/scrape/:id/results — Get job results
 */
router.get('/:id/results', (req: Request, res: Response) => {
  const job = getJob(req.params.id as string);
  if (!job) {
    return res.status(404).json({ error: 'Job not found' });
  }

  if (job.status === 'pending' || job.status === 'running') {
    return res.json({
      jobId: job.id,
      status: job.status,
      progress: job.progress,
      leads: [],
      total: 0,
      message: 'Job is still running. Check back later.',
    });
  }

  const leads = getJobLeads(job.id);
  return res.json({
    jobId: job.id,
    status: job.status,
    leads,
    total: leads.length,
  });
});

export default router;
