import { NextResponse } from 'next/server';
import {
  getConfig, saveConfig, listConfigs, scanAndTrigger,
  startScanner, getProcessedIssues, resetProcessedIssue,
  type GitLabAutofixConfig,
} from '@/lib/issue-scanner-gitlab';
import { startPipeline } from '@/lib/pipeline';

// GET /api/issue-scanner-gitlab?project=PATH
export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const projectPath = searchParams.get('project');
  if (projectPath) {
    return NextResponse.json({
      config: getConfig(projectPath),
      processed: getProcessedIssues(projectPath),
    });
  }
  return NextResponse.json({ configs: listConfigs() });
}

// POST /api/issue-scanner-gitlab
export async function POST(req: Request) {
  const body = await req.json();

  if (body.action === 'save-config') {
    const c: GitLabAutofixConfig = {
      projectPath: body.projectPath,
      projectName: body.projectName,
      enabled: !!body.enabled,
      interval: body.interval || 30,
      labels: body.labels || [],
      baseBranch: body.baseBranch || '',
      baseBranchRule: body.baseBranchRule || 'milestone',
      mrTitleTemplate: body.mrTitleTemplate || '',
      mrBodyTemplate: body.mrBodyTemplate || '',
      assigneeFilter: body.assigneeFilter ?? 'me',
    };
    saveConfig(c);
    startScanner();
    return NextResponse.json({ ok: true });
  }

  if (body.action === 'scan') {
    const c = getConfig(body.projectPath);
    if (!c) return NextResponse.json({ error: 'Not configured' }, { status: 400 });
    return NextResponse.json(scanAndTrigger(c));
  }

  if (body.action === 'trigger') {
    const c = getConfig(body.projectPath);
    const projectName = c?.projectName || body.projectName;
    try {
      const pipeline = startPipeline('gitlab-issue-fix-and-review', {
        issue_id: String(body.issueId),
        project: projectName,
        base_branch: body.baseBranch || c?.baseBranch || 'auto',
        base_branch_rule: c?.baseBranchRule || 'milestone',
        mr_title_template: c?.mrTitleTemplate || '',
        mr_body_template: c?.mrBodyTemplate || '',
        extra_context: body.context || '',
      });
      return NextResponse.json({ ok: true, pipelineId: pipeline.id });
    } catch (e) {
      return NextResponse.json({ ok: false, error: String(e) }, { status: 500 });
    }
  }

  if (body.action === 'reset') {
    resetProcessedIssue(body.projectPath, body.issueId);
    return NextResponse.json({ ok: true });
  }

  if (body.action === 'retry') {
    resetProcessedIssue(body.projectPath, body.issueId);
    const c = getConfig(body.projectPath);
    const projectName = c?.projectName || body.projectName;
    try {
      const pipeline = startPipeline('gitlab-issue-fix-and-review', {
        issue_id: String(body.issueId),
        project: projectName,
        base_branch: c?.baseBranch || 'auto',
        base_branch_rule: c?.baseBranchRule || 'milestone',
        mr_title_template: c?.mrTitleTemplate || '',
        mr_body_template: c?.mrBodyTemplate || '',
        extra_context: body.context || '',
      });
      return NextResponse.json({ ok: true, pipelineId: pipeline.id });
    } catch (e) {
      return NextResponse.json({ ok: false, error: String(e) }, { status: 500 });
    }
  }

  return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
}
