import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

const validateApiKey = (request: NextRequest) => {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return NextResponse.json({ error: "Unauthorized: Missing Bearer token" }, { status: 401 });
  }

  const token = authHeader.split(" ")[1];
  if (!process.env.API_KEY || token !== process.env.API_KEY) {
    return NextResponse.json({ error: "Forbidden: Invalid API Key" }, { status: 403 });
  }

  return null;
};

export async function GET(request: NextRequest) {
  const authError = validateApiKey(request);
  if (authError) {
    return authError;
  }

  const issueUrl = new URL(request.url).searchParams.get("issue_url");
  if (!issueUrl) {
    return NextResponse.json({ error: "Missing issue_url" }, { status: 400 });
  }

  try {
    const latestTask = await prisma.task.findFirst({
      where: {
        description: { contains: issueUrl },
      },
      select: {
        id: true,
        status: true,
        created_at: true,
      },
      orderBy: {
        created_at: "desc",
      },
    });

    if (!latestTask) {
      return NextResponse.json({
        issue_url: issueUrl,
        exists: false,
      });
    }

    return NextResponse.json({
      issue_url: issueUrl,
      exists: true,
      task_id: latestTask.id,
      status: latestTask.status,
      created_at: latestTask.created_at.toISOString(),
    });
  } catch (error) {
    console.error("[Issue Exists API Error]", error);
    return NextResponse.json(
      { error: "InternalError" },
      { status: 500 }
    );
  }
}
