import { describe, expect, it, vi } from "vitest";
import { deleteAssignment } from "../index.js";

describe("deleteAssignment", () => {
  it("deletes an assignment without demand link", async () => {
    const db = {
      assignment: {
        findUnique: vi.fn().mockResolvedValue({
          id: "assignment_1",
          projectId: "project_1",
          resourceId: "resource_1",
          demandRequirementId: null,
        }),
        delete: vi.fn().mockResolvedValue({}),
      },
      demandRequirement: {
        findUnique: vi.fn(),
        update: vi.fn(),
      },
    };

    const result = await deleteAssignment(db as never, "assignment_1");

    expect(result).toEqual({
      deletedId: "assignment_1",
      projectId: "project_1",
      resourceId: "resource_1",
      reopenedDemandId: null,
    });
    expect(db.assignment.delete).toHaveBeenCalledWith({
      where: { id: "assignment_1" },
    });
    expect(db.demandRequirement.findUnique).not.toHaveBeenCalled();
  });

  it("re-opens a COMPLETED demand when its assignment is deleted", async () => {
    const db = {
      assignment: {
        findUnique: vi.fn().mockResolvedValue({
          id: "assignment_1",
          projectId: "project_1",
          resourceId: "resource_1",
          demandRequirementId: "demand_1",
        }),
        delete: vi.fn().mockResolvedValue({}),
      },
      demandRequirement: {
        findUnique: vi.fn().mockResolvedValue({
          id: "demand_1",
          headcount: 0,
          status: "COMPLETED",
        }),
        update: vi.fn().mockResolvedValue({}),
      },
    };

    const result = await deleteAssignment(db as never, "assignment_1");

    expect(result).toEqual({
      deletedId: "assignment_1",
      projectId: "project_1",
      resourceId: "resource_1",
      reopenedDemandId: "demand_1",
    });
    expect(db.demandRequirement.update).toHaveBeenCalledWith({
      where: { id: "demand_1" },
      data: { headcount: 1, status: "ACTIVE" },
    });
  });

  it("increments headcount on an ACTIVE demand when its assignment is deleted", async () => {
    const db = {
      assignment: {
        findUnique: vi.fn().mockResolvedValue({
          id: "assignment_1",
          projectId: "project_1",
          resourceId: "resource_1",
          demandRequirementId: "demand_2",
        }),
        delete: vi.fn().mockResolvedValue({}),
      },
      demandRequirement: {
        findUnique: vi.fn().mockResolvedValue({
          id: "demand_2",
          headcount: 2,
          status: "ACTIVE",
        }),
        update: vi.fn().mockResolvedValue({}),
      },
    };

    const result = await deleteAssignment(db as never, "assignment_2");

    expect(result.reopenedDemandId).toBe("demand_2");
    expect(db.demandRequirement.update).toHaveBeenCalledWith({
      where: { id: "demand_2" },
      data: { headcount: 3, status: "ACTIVE" },
    });
  });
});
