import { NextRequest, NextResponse } from "next/server";
import { getCardById } from "../getCardById";
import { saveApplication } from "../saveApplication";
import { logger } from "@/lib/pinoLogger";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const vparams = await params;
  const id = vparams.id;

  logger.info(`GET /api/apply/${id} - called`);

  if (!id) {
    logger.warn("GET request missing card ID");
    return NextResponse.json({ error: "Card ID required" }, { status: 400 });
  }

  try {
    const card = await getCardById(Number(id));
    if (!card) {
      logger.warn(`Card not found for ID: ${id}`);
      return NextResponse.json({ error: "Card not found" }, { status: 404 });
    }

    logger.info(`Card fetched successfully: ID ${id}`);
    return NextResponse.json(card);
  } catch (error) {
    logger.error({ err: error }, `Error fetching card with ID ${id}`);
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const vparams = await params;
    const id = vparams.id;
    const data = await req.json();

    logger.info(`POST /api/apply/${id} - Application attempt`, { body: data });

    if (
      !id ||
      !data.name ||
      !data.email ||
      !data.phone ||
      !data.salary ||
      data.agree !== true
    ) {
      logger.warn("POST request missing or invalid fields", { id, body: data });
      return NextResponse.json({ error: "Missing or invalid fields" }, { status: 400 });
    }

    const result = await saveApplication({
      ...data,
      cardId: Number(id),
    });

    if (result.success) {
      logger.info(`Application saved successfully`, {
        id,
        insertId: result.insertId,
      });
      return NextResponse.json({
        message: "Application saved",
        id: result.insertId,
      });
    } else {
      logger.error(`Failed to save application`, { id, error: result.error });
      return NextResponse.json(
        { error: result.error || "Failed to save application" },
        { status: 500 }
      );
    }
  } catch (error) {
    logger.error({ err: error }, `POST /api/apply/${(await params).id} - exception`);
    return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
  }
}
