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

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

async function getOrgId(userId: string) {
}

async function nextNumber(orgId: string): Promise<string> {
  const count = await prisma.interventionOrder.count({ where: { organizationId: orgId } });
  return `INT-${String(count + 1).padStart(4, "0")}`;
}

// GET /api/interventions
export async function GET(req: NextRequest) {
  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 { searchParams } = new URL(req.url);
    const search   = searchParams.get("search")?.trim() ?? "";
    const status   = searchParams.get("status") ?? "";
    const priority = searchParams.get("priority") ?? "";

    const interventions = await prisma.interventionOrder.findMany({
      where: {
        organizationId: orgId,
        ...(status   && { status:   status   as any }),
        ...(priority && { priority: priority as any }),
        ...(search   && {
          OR: [
            { title:    { contains: search, mode: "insensitive" } },
            { number:   { contains: search, mode: "insensitive" } },
            { location: { contains: search, mode: "insensitive" } },
          ],
        }),
      },
      include: {
        customer: { select: { id: true, name: true, email: true, phone: true } },
        invoice:  { select: { id: true, number: true, status: true } },
      },
      orderBy: { createdAt: "desc" },
    });

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

// POST /api/interventions
export async function POST(req: NextRequest) {
  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 body = await req.json().catch(() => null);
    if (!body) return NextResponse.json({ success: false, error: "Corps de requête invalide" }, { status: 400 });

    const parsed = createSchema.safeParse(body);
    if (!parsed.success) {
      console.error("[POST /api/interventions] Validation:", parsed.error.flatten());
      return NextResponse.json({ success: false, error: "Données invalides", details: parsed.error.flatten() }, { status: 400 });
    }

    const number = await nextNumber(orgId);
    const { scheduledAt, materials, customerId, technicianId, ...rest } = parsed.data;

    const intervention = await prisma.interventionOrder.create({
      data: {
        ...rest,
        organizationId: orgId,
        number,
        ...(customerId   ? { customerId }               : {}),
        ...(technicianId ? { technicianId }             : {}),
        ...(scheduledAt  ? { scheduledAt: new Date(scheduledAt) } : {}),
        ...(materials    ? { materials }                : {}),
      },
      include: {
        customer: { select: { id: true, name: true, email: true, phone: true } },
      },
    });

    return NextResponse.json({ success: true, data: intervention }, { status: 201 });
  } catch (err: any) {
    console.error("[POST /api/interventions]", err);
    return NextResponse.json({
      success: false,
      error: "Erreur serveur",
      detail: err?.message ?? String(err),
    }, { status: 500 });
  }
}
