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

// ─── Helpers ──────────────────────────────────────────────────

async function getOrgId(userId: string) {
}

// ─── Validation schémas ───────────────────────────────────────

const journalLineSchema = z.object({
  accountCode: z.string().min(1, "Code compte requis"),
  accountLabel: z.string().min(1, "Libellé compte requis"),
  debit: z.number().min(0).default(0),
  credit: z.number().min(0).default(0),
  description: z.string().optional(),
});

const createJournalEntrySchema = z.object({
  date: z.string().datetime({ offset: true }).or(z.string().regex(/^\d{4}-\d{2}-\d{2}$/)),
  reference: z.string().optional(),
  description: z.string().min(1, "Description requise"),
  type: z.enum(["MANUAL", "INVOICE", "EXPENSE", "PAYMENT", "BANK", "BANK_IMPORT", "ADJUSTMENT", "OPENING", "CLOSING"]).default("MANUAL"),
  lines: z
    .array(journalLineSchema)
    .min(2, "Au moins 2 lignes requises")
    .refine(
      (lines) => {
        const totalDebit = lines.reduce((s, l) => s + l.debit, 0);
        const totalCredit = lines.reduce((s, l) => s + l.credit, 0);
        return Math.abs(totalDebit - totalCredit) < 0.01;
      },
      { message: "Total débit doit égaler total crédit (écriture équilibrée)" }
    ),
});

// ─── GET /api/journal-entries ─────────────────────────────────

export async function GET(req: NextRequest) {
  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 { searchParams } = new URL(req.url);
  const page = Math.max(1, parseInt(searchParams.get("page") ?? "1", 10));
  const limit = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "20", 10)));
  const type = searchParams.get("type") ?? undefined;
  const from = searchParams.get("from");
  const to = searchParams.get("to");

  const where: any = { organizationId: orgId };
  if (type) where.type = type;
  if (from || to) {
    where.date = {};
    if (from) where.date.gte = new Date(from);
    if (to) {
      const toDate = new Date(to);
      toDate.setHours(23, 59, 59, 999);
      where.date.lte = toDate;
    }
  }

  const [entries, total] = await prisma.$transaction([
    prisma.journalEntry.findMany({
      where,
      include: {
        lines: {
          orderBy: { order: "asc" },
        },
      },
      orderBy: { date: "desc" },
      skip: (page - 1) * limit,
      take: limit,
    }),
    prisma.journalEntry.count({ where }),
  ]);

  return NextResponse.json({
    success: true,
    data: entries.map((e) => ({
      ...e,
      lines: e.lines.map((l) => ({
        ...l,
        debit: Number(l.debitAmount),
        credit: Number(l.creditAmount),
      })),
    })),
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit),
    },
  });
}

// ─── POST /api/journal-entries ────────────────────────────────

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

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

  const { date, reference, description, type, lines } = parsed.data;

  // Générer un numéro d'écriture séquentiel (format: JNL-YYYY-NNNN)
  const year = new Date(date).getFullYear();
  const lastEntry = await prisma.journalEntry.findFirst({
    where: { organizationId: orgId, number: { startsWith: `JNL-${year}-` } },
    orderBy: { number: "desc" },
    select: { number: true },
  });

  let counter = 1;
  if (lastEntry?.number) {
    const parts = lastEntry.number.split("-");
    const lastNum = parseInt(parts[parts.length - 1] ?? "0", 10);
    counter = lastNum + 1;
  }
  const entryNumber = `JNL-${year}-${String(counter).padStart(4, "0")}`;

  const entry = await prisma.journalEntry.create({
    data: {
      organizationId: orgId,
      number: entryNumber,
      date: new Date(date),
      reference: reference ?? null,
      description,
      type,
      isManual: true,
      lines: {
        create: lines.map((l, i) => ({
          accountCode: l.accountCode,
          accountLabel: l.accountLabel,
          debitAmount: l.debit,
          creditAmount: l.credit,
          description: l.description ?? null,
          order: i,
        })),
      },
    },
    include: { lines: true },
  });

  return NextResponse.json({ success: true, data: entry }, { status: 201 });
}
