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 {
  InvalidStatusTransitionError,
  MissingRequiredFieldError,
  RequestNotFoundError,
} from "../lib/errors.generated";
import {
  approvedRequest,
  cancelledRequest,
  pendingRequest,
  rejectedRequest,
  withdrawnRequest,
} from "../testing/fixtures";
import { run } from "./cancelApprovalRequest";

describe("cancelApprovalRequest", () => {
  const ctx: CommandContext = {
    actorId: "user-admin-1",
    permissions: ["approval:request:cancelApprovalRequest"],
  };

  it("transitions PENDING to CANCELLED and stamps resolvedAt", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = {
      ...pendingRequest,
      status: "CANCELLED" as const,
      resolvedAt: new Date("2024-04-01T00:00:00.000Z"),
      updatedAt: new Date("2024-04-01T00:00:00.000Z"),
    };
    spies.select.mockReturnValue(pendingRequest);
    spies.update.mockReturnValue(updated);

    const result = await run(db, { approvalRequestId: pendingRequest.id, reason: "stuck" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest.status).toBe("CANCELLED");
      expect(result.value.approvalRequest.resolvedAt).not.toBeNull();
    }
    const setCall = spies.set.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(setCall.status).toBe("CANCELLED");
    expect(setCall.resolvedAt).toBeInstanceOf(Date);
  });

  it("writes an ApprovalDecision row with decision = CANCEL, approvalStepId null, and approvalRequestId set", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(pendingRequest);
    spies.update.mockReturnValue({ ...pendingRequest, status: "CANCELLED" });

    await run(db, { approvalRequestId: pendingRequest.id, reason: "stuck" }, ctx);

    expect(spies.insert).toHaveBeenCalled();
    const decisionRow = spies.values.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(decisionRow.decision).toBe("CANCEL");
    expect(decisionRow.approvalRequestId).toBe(pendingRequest.id);
  });

  it("records ctx.actorId on the decision row's decidedByUserId", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(pendingRequest);
    spies.update.mockReturnValue({ ...pendingRequest, status: "CANCELLED" });

    await run(db, { approvalRequestId: pendingRequest.id, reason: "stuck" }, ctx);

    const decisionRow = spies.values.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(decisionRow.decidedByUserId).toBe(ctx.actorId);
  });

  it("writes the supplied reason to the decision row's comment", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(pendingRequest);
    spies.update.mockReturnValue({ ...pendingRequest, status: "CANCELLED" });

    await run(
      db,
      { approvalRequestId: pendingRequest.id, reason: "requester left the company" },
      ctx,
    );

    const decisionRow = spies.values.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(decisionRow.comment).toBe("requester left the company");
  });

  it("throws MISSING_REQUIRED_FIELD when reason is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(pendingRequest);

    const result = await run(db, { approvalRequestId: pendingRequest.id, reason: "   " }, ctx);

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

  it("throws INVALID_STATUS_TRANSITION when the request is APPROVED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(approvedRequest);

    const result = await run(db, { approvalRequestId: approvedRequest.id, reason: "stuck" }, ctx);

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

  it("throws INVALID_STATUS_TRANSITION when the request is REJECTED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(rejectedRequest);

    const result = await run(db, { approvalRequestId: rejectedRequest.id, reason: "stuck" }, ctx);

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

  it("throws INVALID_STATUS_TRANSITION when the request is WITHDRAWN", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(withdrawnRequest);

    const result = await run(db, { approvalRequestId: withdrawnRequest.id, reason: "stuck" }, ctx);

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

  it("throws INVALID_STATUS_TRANSITION when the request is already CANCELLED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(cancelledRequest);

    const result = await run(db, { approvalRequestId: cancelledRequest.id, reason: "stuck" }, ctx);

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

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

    const result = await run(db, { approvalRequestId: "nonexistent", reason: "stuck" }, ctx);

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