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

async function getOrgId(userId: string) {
}

const updateSchema = z.object({
  status: z.enum(["ACTIVE", "PAUSED", "ENDED"]).optional(),
  endDate: z.string().nullable().optional(),
  subject: z.string().optional(),
  notes: z.string().optional(),
  terms: z.string().optional(),
  reference: z.string().optional(),
}).strict();

// ─── GET /api/recurring-invoices/[id] ─────────────────────────

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

  const { id } = await params;
  const recurring = await prisma.recurringInvoice.findFirst({
    where: { id, organizationId: orgId },
    include: {
      customer: { select: { id: true, name: true, email: true } },
      items: { orderBy: { order: "asc" } },
    },
  });

  if (!recurring) return NextResponse.json({ success: false, error: "Introuvable" }, { status: 404 });

  return NextResponse.json({ success: true, data: recurring });
}

// ─── PATCH /api/recurring-invoices/[id] ───────────────────────

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

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

  const body = await req.json().catch(() => null);
  if (!body) return NextResponse.json({ success: false, error: "Corps invalide" }, { status: 400 });

  const parsed = updateSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ success: false, error: "Données invalides", details: parsed.error.flatten() }, { status: 422 });
  }

  const { endDate, ...rest } = parsed.data;
  const updated = await prisma.recurringInvoice.update({
    where: { id },
    data: {
      ...rest,
      ...(endDate !== undefined && { endDate: endDate ? new Date(endDate) : null }),
    },
    include: {
      customer: { select: { id: true, name: true, email: true } },
      items: { orderBy: { order: "asc" } },
    },
  });

  return NextResponse.json({ success: true, data: updated });
}

// ─── DELETE /api/recurring-invoices/[id] ──────────────────────

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

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

  await prisma.recurringInvoice.delete({ where: { id } });

  return NextResponse.json({ success: true });
}
