

import { NextRequest, NextResponse } from "next/server"
import { runEmployeeSync } from "@/jobs/sync-employees"
import { runAttendanceSync } from "@/jobs/sync-attendance"
import { db } from "@/lib/db"
import type { PrismaClient } from "@prisma/client"

const prisma = db as PrismaClient

// ── GET — fetch sync logs ─────────────────────────────────────────────────────

export async function GET() {
  try {
    const logs = await prisma.zKSyncLog.findMany({
      orderBy: { startedAt: "desc" },
      take: 20,
    })
    return NextResponse.json({ logs })
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Unknown error" },
      { status: 500 }
    )
  }
}

// ── POST — trigger a sync ─────────────────────────────────────────────────────

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { type, startDate, endDate } = body as {
      type: "employees" | "attendance" | "both"
      startDate?: string
      endDate?: string
    }

    if (!["employees", "attendance", "both"].includes(type)) {
      return NextResponse.json({ error: "type must be employees | attendance | both" }, { status: 400 })
    }

    const results: Record<string, unknown> = {}

    if (type === "employees" || type === "both") {
      results.employees = await runEmployeeSync()
    }

    if (type === "attendance" || type === "both") {
      const opts =
        startDate && endDate
          ? { startTime: `${startDate} 00:00:00`, endTime: `${endDate} 23:59:59` }
          : undefined
      results.attendance = await runAttendanceSync(opts)
    }

    return NextResponse.json({ success: true, results })
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Unknown error" },
      { status: 500 }
    )
  }
}