import { NextResponse } from "next/server"
import { z } from "zod"
import { createMachineSession } from "@/server/machines-session"
import { applyCorsHeaders, createCorsPreflight, jsonWithCors } from "@/server/cors"

const sessionSchema = z.object({
  machineToken: z.string().min(1),
  rememberMe: z.boolean().optional(),
})

const CORS_METHODS = "POST, OPTIONS"

export async function OPTIONS(request: Request) {
  return createCorsPreflight(request.headers.get("origin"), CORS_METHODS)
}

export async function POST(request: Request) {
  if (request.method !== "POST") {
    return jsonWithCors({ error: "Método não permitido" }, 405, request.headers.get("origin"), CORS_METHODS)
  }

  let payload
  try {
    const raw = await request.json()
    payload = sessionSchema.parse(raw)
  } catch (error) {
    return jsonWithCors(
      { error: "Payload inválido", details: error instanceof Error ? error.message : String(error) },
      400,
      request.headers.get("origin"),
      CORS_METHODS
    )
  }

  try {
    const session = await createMachineSession(payload.machineToken, payload.rememberMe ?? true)
    const response = NextResponse.json(
      {
        ok: true,
        machine: session.machine,
        session: session.response,
      },
      { status: 200 }
    )

    session.headers.forEach((value, key) => {
      response.headers.set(key, value)
    })

    applyCorsHeaders(response, request.headers.get("origin"), CORS_METHODS)

    return response
  } catch (error) {
    console.error("[machines.sessions] Falha ao criar sessão", error)
    return jsonWithCors({ error: "Falha ao autenticar máquina" }, 500, request.headers.get("origin"), CORS_METHODS)
  }
}
