import { type NextRequest, NextResponse } from "next/server"
import { voucherDb, applicationDb } from "@/lib/db"
import type { ApiResponse } from "@/lib/types"

export async function POST(request: NextRequest) {
  try {
    const { serialNumber, pin } = await request.json()

    if (!serialNumber || !pin) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "Serial number and PIN are required",
        },
        { status: 400 },
      )
    }

    // Validate voucher
    const voucher = await voucherDb.findBySerialAndPin(serialNumber, pin)

    if (!voucher) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "Invalid voucher credentials",
        },
        { status: 401 },
      )
    }

    if (voucher.used && !voucher.userId) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "This voucher has already been used",
        },
        { status: 401 },
      )
    }

    // Generate user ID if voucher not used yet
    let userId = voucher.userId
    if (!userId) {
      userId = `user_${Date.now()}`
      await voucherDb.markAsUsed(serialNumber, userId)

      // Create initial application
      await applicationDb.create({
        userId,
        voucherSerialNumber: serialNumber,
        submitted: false,
        biodata: {
          firstName: "",
          lastName: "",
          dateOfBirth: "",
          gender: "",
          nationality: "",
          stateOfOrigin: "",
          phoneNumber: "",
          email: "",
        },
        address: {
          permanentAddress: "",
          permanentCity: "",
          permanentState: "",
          permanentCountry: "",
          sameAsPermanent: false,
        },
        education: { entries: [] },
        program: {
          firstChoice: "",
          studyMode: "",
          entryLevel: "",
          personalStatement: "",
        },
        guardian: {
          guardianName: "",
          relationship: "",
          phoneNumber: "",
          address: "",
          emergencyName: "",
          emergencyPhone: "",
        },
        scholarship: { applyingForScholarship: false },
        referee: { referees: [] },
        uploads: { files: [] },
        declaration: {
          truthfulnessDeclaration: false,
          accuracyDeclaration: false,
          consequencesDeclaration: false,
          updatesDeclaration: false,
          termsDeclaration: false,
          signature: "",
          date: "",
        },
      })
    }

    // In a real app, you'd set up proper session/JWT here
    const response = NextResponse.json<ApiResponse>({
      success: true,
      data: { userId, serialNumber },
      message: "Login successful",
    })

    // Set session cookie (simplified)
    response.cookies.set("session", JSON.stringify({ userId, serialNumber }), {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      maxAge: 60 * 60 * 24 * 7, // 7 days
    })

    return response
  } catch (error) {
    console.error("Login error:", error)
    return NextResponse.json<ApiResponse>(
      {
        success: false,
        error: "Internal server error",
      },
      { status: 500 },
    )
  }
}
