import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { NextResponse } from "next/server";

import { serializeSales } from "@/features/sales/lib/serialize-sales";
import { salesInputSchema } from "@/features/sales/schemas/sales.schema";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { requireApiAccess } from "@/lib/authorization";
import { resolveMasterCode } from "@/lib/master-code";
import { prisma } from "@/lib/prisma";

export async function GET(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const data = await prisma.sales.findMany({
    include: {
      bankAccounts: {
        include: {
          bank: true
        }
      }
    },
    orderBy: [{ createdAt: "desc" }]
  });

  return NextResponse.json({ data: data.map(serializeSales) });
}

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const parsed = salesInputSchema.safeParse(await request.json());
  if (!parsed.success) {
    return NextResponse.json(
      { message: "Validasi gagal", errors: parsed.error.flatten().fieldErrors },
      { status: 400 }
    );
  }

  try {
    const bankIds = parsed.data.bank_accounts.map((account) => BigInt(account.bank_id));

    const banks = await prisma.bank.findMany({
      where: { id: { in: bankIds }, status: "ACTIVE" }
    });

    if (banks.length !== bankIds.length) {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { bank_accounts: ["Semua rekening harus memilih bank aktif dari master"] } },
        { status: 400 }
      );
    }

    const resolvedCode = await resolveMasterCode({
      role: auth.user.role,
      prefix: "SEL",
      requestedCode: parsed.data.code,
      countExisting: () => prisma.sales.count({ where: { code: { startsWith: "SEL" } } }),
      exists: async (code) => (await prisma.sales.count({ where: { code } })) > 0
    });

    if (!resolvedCode.ok) {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { code: [resolvedCode.message] } },
        { status: 400 }
      );
    }

    const sales = await prisma.sales.create({
      data: {
        code: resolvedCode.code,
        name: parsed.data.name,
        identityType: parsed.data.identity_type,
        identityNumber: parsed.data.identity_number,
        mobilePhone: parsed.data.mobile_phone || null,
        email: parsed.data.email || null,
        address: parsed.data.address || null,
        notes: parsed.data.notes || null,
        joinDate: new Date(parsed.data.join_date),
        bankAccounts: {
          create: parsed.data.bank_accounts.map((account) => ({
            bankId: BigInt(account.bank_id),
            accountNumber: account.account_number
          }))
        }
      },
      include: {
        bankAccounts: { include: { bank: true } }
      }
    });

    await createAuditTrailSafe({
      userId: auth.user.id,
      action: "SELLER_CREATED",
      entityType: "SELLER",
      entityId: sales.id,
      method: request.method,
      pathname: new URL(request.url).pathname,
      statusCode: 201,
      summary: `Sales ${sales.code} dibuat`
    });

    return NextResponse.json({ data: serializeSales(sales) }, { status: 201 });
  } catch (error) {
    if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
      return NextResponse.json(
        { message: "Validasi gagal", errors: { identity_number: ["Kode sales atau identitas sudah dipakai"] } },
        { status: 409 }
      );
    }
    throw error;
  }
}
