import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { z } from "zod";

const updateSchema = z.object({
  title:        z.string().min(1).optional(),
  description:  z.string().optional(),
  location:     z.string().optional(),
  priority:     z.enum(["LOW", "NORMAL", "HIGH", "URGENT"]).optional(),
  customerId:   z.string().nullable().optional(),
  technicianId: z.string().nullable().optional(),
  scheduledAt:  z.string().nullable().optional(),
  observations: z.string().optional(),
  resolution:   z.string().optional(),
  duration:     z.number().int().min(0).optional(),
  materials:    z.array(z.object({
    name: z.string(),
    quantity: z.number().default(1),
    unitPrice: z.number().default(0),
  })).optional(),
  clientSignature: z.string().optional(),
});

async function getOrgId(userId: string) {
}

// GET /api/interventions/[id]
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

    const { id } = await params;
    const intervention = await prisma.interventionOrder.findFirst({
      where: { id, organizationId: orgId },
      include: {
        customer: true,
        invoice:  { select: { id: true, number: true, status: true, total: true } },
      },
    });

    if (!intervention) return NextResponse.json({ success: false, error: "Bon introuvable" }, { status: 404 });
    return NextResponse.json({ success: true, data: intervention });
  } catch (err) {
    console.error("[GET /api/interventions/[id]]", err);
    return NextResponse.json({ success: false, error: "Erreur serveur" }, { status: 500 });
  }
}

// PATCH /api/interventions/[id]
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

    const { id } = await params;
    const existing = await prisma.interventionOrder.findFirst({ where: { id, organizationId: orgId } });
    if (!existing) return NextResponse.json({ success: false, error: "Bon introuvable" }, { status: 404 });

    const body = await req.json().catch(() => ({}));
    const parsed = updateSchema.safeParse(body);
    if (!parsed.success) return NextResponse.json({ success: false, error: "Données invalides" }, { status: 400 });

    const { scheduledAt, materials, customerId, technicianId, ...rest } = parsed.data;

    const updated = await prisma.interventionOrder.update({
      where: { id },
      data: {
        ...rest,
        ...(customerId   !== undefined && { customerId:   customerId   ?? null }),
        ...(technicianId !== undefined && { technicianId: technicianId ?? null }),
        ...(scheduledAt  !== undefined && { scheduledAt:  scheduledAt ? new Date(scheduledAt) : null }),
        ...(materials    !== undefined && { materials }),
      },
      include: {
        customer: { select: { id: true, name: true, email: true, phone: true } },
        invoice:  { select: { id: true, number: true, status: true } },
      },
    });

    return NextResponse.json({ success: true, data: updated });
  } catch (err) {
    console.error("[PATCH /api/interventions/[id]]", err);
    return NextResponse.json({ success: false, error: "Erreur serveur" }, { status: 500 });
  }
}

// DELETE /api/interventions/[id]
export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

    const { id } = await params;
    const existing = await prisma.interventionOrder.findFirst({ where: { id, organizationId: orgId } });
    if (!existing) return NextResponse.json({ success: false, error: "Bon introuvable" }, { status: 404 });

    await prisma.interventionOrder.delete({ where: { id } });
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("[DELETE /api/interventions/[id]]", err);
    return NextResponse.json({ success: false, error: "Erreur serveur" }, { status: 500 });
  }
}
