import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...draftPolicy, name: "Renamed" };

    mock.enqueueResults([draftPolicy], [updated]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: draftPolicy.id, name: "Renamed" }, ctx),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalPolicy.name).toBe("Renamed");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("updates the description of a DRAFT policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...draftPolicy, description: "New description" };

    mock.enqueueResults([draftPolicy], [updated]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: draftPolicy.id, description: "New description" }, ctx),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalPolicy.description).toBe("New description");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("replaces the steps subtree atomically and prior step rows are gone", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [draftPolicy],
      [{ id: "old-step-1" }, { id: "old-step-2" }],
      [],
      [],
      // Insert returns the new step rows so the assignee insert can reference them
      [
        { id: "new-step-1", stepOrder: 1 },
        { id: "new-step-2", stepOrder: 2 },
      ],
      [],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          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(mock.deletes).toHaveLength(2);
    // Two inserts: steps then assignees
    expect(mock.inserts).toHaveLength(2);
  });

  it("rejects updating purpose after creation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([draftPolicy]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { 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(mock.updates).toHaveLength(0);
  });

  it("throws INVALID_STATUS_TRANSITION when policy is ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activePolicy]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactivePolicy]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([draftPolicy]);
      const result = await mock.withTx((trx) => run(trx, { id: draftPolicy.id, steps: [] }, ctx));
      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(PolicyHasNoStepsError);
      }
    }

    // DUPLICATE_STEP_ORDER
    {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([draftPolicy]);
      const result = await mock.withTx((trx) =>
        run(
          trx,
          {
            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 mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([draftPolicy]);
      const result = await mock.withTx((trx) =>
        run(
          trx,
          {
            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 mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([draftPolicy]);
      const result = await mock.withTx((trx) =>
        run(
          trx,
          {
            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 mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([draftPolicy]);
      const result = await mock.withTx((trx) =>
        run(
          trx,
          {
            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 mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([draftPolicy]);
      const result = await mock.withTx((trx) =>
        run(
          trx,
          {
            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 mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([draftPolicy]);

      const result = await mock.withTx((trx) => run(trx, { id: draftPolicy.id, name }, ctx));

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