import { NextRequest, NextResponse } from "next/server"
import { auth }                      from "@/lib/auth"
import { clockIn, clockOut }         from "@/features/attendance/service"
import { clockSchema }               from "@/features/attendance/schema"

export const runtime = "nodejs"

export async function POST(req: NextRequest) {
  try {
    const session = await auth()
    if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const body   = await req.json()
    const parsed = clockSchema.safeParse(body)

    if (!parsed.success) {
      return NextResponse.json(
        { error: "Validation error", details: parsed.error.errors },
        { status: 400 }
      )
    }

    const { employeeId, type } = parsed.data
    const branchId = body.branchId as string | undefined

    const record = type === "in"
      ? await clockIn(employeeId, branchId)
      : await clockOut(employeeId)

    return NextResponse.json(record)
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "Clock action failed"
    return NextResponse.json({ error: msg }, { status: 400 })
  }
}