import { describe, it, expect, afterEach } from "vitest";
import prisma from "../config/database";
import { createProject } from "../services/projects.service";
import { createOrder } from "../services/orders.service";

const createdProjectIds: number[] = [];
const createdOrderIds: number[] = [];

afterEach(async () => {
  for (const id of createdProjectIds)
    await prisma.projects.deleteMany({ where: { id } });
  for (const id of createdOrderIds)
    await prisma.orders.deleteMany({ where: { id } });
  createdProjectIds.length = 0;
  createdOrderIds.length = 0;
  await prisma.number_sequences.deleteMany({ where: { type: "shared" } });
});

const baseOrder = {
  status: "prijata" as const,
  currency: "CZK",
  language: "cs",
  vat_rate: 21,
  apply_vat: true,
  exchange_rate: 1,
};

/**
 * Fail loudly (instead of the old `if (!("id" in res)) return;`, which silently
 * passed the test when a create failed) while still narrowing the union via the
 * `in` operator so the success-branch fields stay typed.
 */
function failResult(res: unknown): never {
  throw new Error(`expected a success result, got ${JSON.stringify(res)}`);
}

describe("createOrder (manual, optional linked project)", () => {
  it("creates an order AND a project sharing one number when create_project=true", async () => {
    const res = await createOrder({
      ...baseOrder,
      scope_title: "Ruční zakázka",
      create_project: true,
    });
    if (!("id" in res)) failResult(res);
    createdOrderIds.push(res.id!);
    expect(res.project_id).toBeTruthy();
    const project = await prisma.projects.findUnique({
      where: { id: res.project_id! },
    });
    if (project) createdProjectIds.push(project.id);
    expect(project?.project_number).toBe(res.order_number);
    expect(project?.order_id).toBe(res.id);
  });

  it("creates only the order when create_project=false", async () => {
    const res = await createOrder({ ...baseOrder, create_project: false });
    if (!("id" in res)) failResult(res);
    createdOrderIds.push(res.id!);
    expect(res.project_id).toBeUndefined();
  });
});

describe("shared pool coherence (tracking)", () => {
  it("order → standalone project → order produce three distinct shared numbers", async () => {
    const o1 = await createOrder({ ...baseOrder, create_project: true });
    if (!("id" in o1)) failResult(o1);
    createdOrderIds.push(o1.id!);
    if (o1.project_id) createdProjectIds.push(o1.project_id);

    const p = await createProject({ name: "Mezi-projekt", status: "aktivni" });
    if (!("project_number" in p)) failResult(p);
    createdProjectIds.push(p.id);

    const o2 = await createOrder({ ...baseOrder, create_project: false });
    if (!("id" in o2)) failResult(o2);
    createdOrderIds.push(o2.id!);

    // All three numbers must be present (non-null) AND distinct.
    expect(o1.order_number).toBeTruthy();
    expect(p.project_number).toBeTruthy();
    expect(o2.order_number).toBeTruthy();
    expect(
      new Set([o1.order_number, p.project_number, o2.order_number]).size,
    ).toBe(3);
  });
});

describe("createProject (manual, standalone)", () => {
  it("assigns a shared number and is not linked to an order", async () => {
    const result = await createProject({
      name: "Test projekt",
      status: "aktivni",
    });
    if (!("project_number" in result)) failResult(result);
    createdProjectIds.push(result.id);
    expect(typeof result.project_number).toBe("string");
    expect(result.project_number!.length).toBeGreaterThan(0);
    expect(result.order_id).toBeNull();
  });

  it("gives consecutive standalone projects distinct numbers", async () => {
    const a = await createProject({ name: "Projekt A", status: "aktivni" });
    const b = await createProject({ name: "Projekt B", status: "aktivni" });
    if ("project_number" in a) createdProjectIds.push(a.id);
    if ("project_number" in b) createdProjectIds.push(b.id);
    expect("project_number" in a && "project_number" in b).toBe(true);
    if ("project_number" in a && "project_number" in b) {
      expect(a.project_number).not.toBe(b.project_number);
    }
  });
});

describe("createOrder with price line item + attachment", () => {
  it("stores a single line item with the entered price", async () => {
    const res = await createOrder({
      ...baseOrder,
      create_project: false,
      items: [
        {
          description: "Práce",
          quantity: 1,
          unit_price: 12345,
          is_included_in_total: true,
        },
      ],
    });
    if (!("id" in res)) failResult(res);
    createdOrderIds.push(res.id!);
    const items = await prisma.order_items.findMany({
      where: { order_id: res.id },
    });
    expect(items.length).toBe(1);
    expect(Number(items[0].unit_price)).toBe(12345);
  });

  it("stores an uploaded PO attachment with the exact bytes", async () => {
    const buf = Buffer.from("%PDF-1.4 fake-attachment-bytes-éí");
    const res = await createOrder(
      { ...baseOrder, create_project: false },
      buf,
      "po.pdf",
    );
    if (!("id" in res)) failResult(res);
    createdOrderIds.push(res.id!);
    const order = await prisma.orders.findUnique({
      where: { id: res.id },
      select: { attachment_name: true, attachment_data: true },
    });
    expect(order?.attachment_name).toBe("po.pdf");
    // Verify the stored content/size, not just truthiness: round-trip the
    // bytes and compare length + value against what we uploaded.
    expect(order?.attachment_data).toBeTruthy();
    const stored = Buffer.from(order!.attachment_data!);
    expect(stored.length).toBe(buf.length);
    expect(stored.equals(buf)).toBe(true);
  });
});
