import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AssigneeUserRoleXorViolatedError,
  DuplicateStepOrderError,
  InvalidMinimumApprovalsError,
  InvalidStatusTransitionError,
  MissingRequiredFieldError,
  PolicyHasNoStepsError,
  PolicyNotFoundError,
  StepHasNoAssigneesError,
} from "../lib/errors.generated";
import { activePolicy, draftPolicy, inactivePolicy } from "../testing/fixtures";
import { run, type UpdateApprovalPolicyInput } from "./updateApprovalPolicy";

describe("updateApprovalPolicy", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["approval:policy:update"],
  };

  it("updates the name of a DRAFT policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...draftPolicy, name: "Renamed" };

    spies.select.mockReturnValueOnce(draftPolicy);
    spies.update.mockReturnValue(updated);

    const result = await run(db, { id: draftPolicy.id, name: "Renamed" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalPolicy.name).toBe("Renamed");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("updates the description of a DRAFT policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...draftPolicy, description: "New description" };

    spies.select.mockReturnValueOnce(draftPolicy);
    spies.update.mockReturnValue(updated);

    const result = await run(db, { id: draftPolicy.id, description: "New description" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalPolicy.description).toBe("New description");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("replaces the steps subtree atomically and prior step rows are gone", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // 1: select policy. 2: select existing step ids for cleanup
    spies.select.mockReturnValueOnce(draftPolicy);
    spies.select.mockReturnValueOnce([{ id: "old-step-1" }, { id: "old-step-2" }]);
    spies.update.mockReturnValue(draftPolicy);
    // Insert returns the new step rows so the assignee insert can reference them
    spies.insert.mockReturnValueOnce([
      { id: "new-step-1", stepOrder: 1 },
      { id: "new-step-2", stepOrder: 2 },
    ]);
    spies.insert.mockReturnValueOnce([]);

    const result = await run(
      db,
      {
        id: draftPolicy.id,
        steps: [
          {
            stepOrder: 1,
            name: "Manager",
            minimumApprovals: 1,
            assignees: [{ userId: "user-1" }],
          },
          {
            stepOrder: 2,
            name: "Director",
            minimumApprovals: 1,
            assignees: [{ roleId: "role-1" }],
          },
        ],
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    // Two deletes: assignees first, then steps
    expect(spies.delete).toHaveBeenCalledTimes(2);
    // Two inserts: steps then assignees
    expect(spies.insert).toHaveBeenCalledTimes(2);
  });

  it("rejects updating purpose after creation", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(draftPolicy);

    const result = await run(
      db,
      { id: draftPolicy.id, purpose: "OTHER" } as unknown as UpdateApprovalPolicyInput,
      ctx,
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalPolicy.purpose).toBe(draftPolicy.purpose);
    }
    // `purpose` is not a recognized input, so no update should be issued.
    expect(spies.update).not.toHaveBeenCalled();
  });

  it("throws INVALID_STATUS_TRANSITION when policy is ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activePolicy);

    const result = await run(db, { id: activePolicy.id, name: "x" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusTransitionError);
    }
  });

  it("throws INVALID_STATUS_TRANSITION when policy is INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePolicy);

    const result = await run(db, { id: inactivePolicy.id, name: "x" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusTransitionError);
    }
  });

  it("throws POLICY_NOT_FOUND for a non-existent policyId", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "missing", name: "x" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(PolicyNotFoundError);
    }
  });

  it("throws shape-specific errors for invalid replacement steps", async () => {
    // POLICY_HAS_NO_STEPS — empty array
    {
      const { db, spies } = createMockDb<Transaction>();
      spies.select.mockReturnValueOnce(draftPolicy);
      const result = await run(db, { id: draftPolicy.id, steps: [] }, ctx);
      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(PolicyHasNoStepsError);
      }
    }

    // DUPLICATE_STEP_ORDER
    {
      const { db, spies } = createMockDb<Transaction>();
      spies.select.mockReturnValueOnce(draftPolicy);
      const result = await run(
        db,
        {
          id: draftPolicy.id,
          steps: [
            { stepOrder: 1, name: "a", assignees: [{ userId: "u1" }] },
            { stepOrder: 1, name: "b", assignees: [{ userId: "u2" }] },
          ],
        },
        ctx,
      );
      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(DuplicateStepOrderError);
      }
    }

    // STEP_HAS_NO_ASSIGNEES
    {
      const { db, spies } = createMockDb<Transaction>();
      spies.select.mockReturnValueOnce(draftPolicy);
      const result = await run(
        db,
        {
          id: draftPolicy.id,
          steps: [{ stepOrder: 1, name: "a", assignees: [] }],
        },
        ctx,
      );
      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(StepHasNoAssigneesError);
      }
    }

    // INVALID_MINIMUM_APPROVALS — zero
    {
      const { db, spies } = createMockDb<Transaction>();
      spies.select.mockReturnValueOnce(draftPolicy);
      const result = await run(
        db,
        {
          id: draftPolicy.id,
          steps: [{ stepOrder: 1, name: "a", minimumApprovals: 0, assignees: [{ userId: "u1" }] }],
        },
        ctx,
      );
      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(InvalidMinimumApprovalsError);
      }
    }

    // ASSIGNEE_USER_ROLE_XOR_VIOLATED — both
    {
      const { db, spies } = createMockDb<Transaction>();
      spies.select.mockReturnValueOnce(draftPolicy);
      const result = await run(
        db,
        {
          id: draftPolicy.id,
          steps: [
            {
              stepOrder: 1,
              name: "a",
              assignees: [{ userId: "u1", roleId: "r1" }],
            },
          ],
        },
        ctx,
      );
      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(AssigneeUserRoleXorViolatedError);
      }
    }

    // ASSIGNEE_USER_ROLE_XOR_VIOLATED — neither
    {
      const { db, spies } = createMockDb<Transaction>();
      spies.select.mockReturnValueOnce(draftPolicy);
      const result = await run(
        db,
        {
          id: draftPolicy.id,
          steps: [{ stepOrder: 1, name: "a", assignees: [{}] }],
        },
        ctx,
      );
      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(AssigneeUserRoleXorViolatedError);
      }
    }
  });

  it("throws MISSING_REQUIRED_FIELD when name is supplied as empty or whitespace", async () => {
    for (const name of ["", "   "]) {
      const { db, spies } = createMockDb<Transaction>();
      spies.select.mockReturnValueOnce(draftPolicy);

      const result = await run(db, { id: draftPolicy.id, name }, ctx);

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
      }
    }
  });
});
