import { NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { shiftInputSchema } from "@/features/shifts/schema"
import { createShift, listShiftsAdmin } from "@/features/shifts/service"

export const runtime = "nodejs"

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

    const shifts = await listShiftsAdmin()
    return NextResponse.json(shifts)
  } catch (error) {
    console.error("Error fetching shifts:", error)
    return NextResponse.json({ error: "Failed to fetch shifts" }, { status: 500 })
  }
}

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

    const body = await req.json()
    const validated = shiftInputSchema.parse(body)

    const shift = await createShift(validated)
    return NextResponse.json(shift, { status: 201 })
  } catch (error) {
    if (error instanceof Error && error.name === "ZodError") {
      return NextResponse.json({ error: "Validation failed", details: error }, { status: 400 })
    }
    console.error("Error creating shift:", error)
    return NextResponse.json({ error: "Failed to create shift" }, { status: 500 })
  }
}
