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 {
  InvalidStatusTransitionError,
  MissingRequiredFieldError,
  RequestNotFoundError,
} from "../lib/errors.generated";
import {
  approvedRequest,
  cancelledRequest,
  pendingRequest,
  rejectedRequest,
  revisionRequestedRequest,
  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 mock = createKyselyMock<Namespace["main-db"]>();
    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"),
    };
    mock.enqueueResults([pendingRequest], [], [updated]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 = mock.updates[0].updateValues();
    expect(setCall.status).toBe("CANCELLED");
    expect(setCall.resolvedAt).toBeInstanceOf(Date);
  });

  it("transitions REVISION_REQUESTED to CANCELLED and stamps resolvedAt", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = {
      ...revisionRequestedRequest,
      status: "CANCELLED" as const,
      resolvedAt: new Date("2024-04-01T00:00:00.000Z"),
      updatedAt: new Date("2024-04-01T00:00:00.000Z"),
    };
    mock.enqueueResults([revisionRequestedRequest], [], [updated]);

    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: revisionRequestedRequest.id, reason: "abandoned" }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest.status).toBe("CANCELLED");
    }
  });

  it("writes an ApprovalDecision row with decision = CANCEL, approvalStepId null, and approvalRequestId set", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pendingRequest], [], [{ ...pendingRequest, status: "CANCELLED" }]);

    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: pendingRequest.id, reason: "stuck" }, ctx),
    );

    expect(mock.inserts.length).toBeGreaterThan(0);
    const decisionRow = mock.inserts[0].insertValues();
    expect(decisionRow.decision).toBe("CANCEL");
    expect(decisionRow.approvalRequestId).toBe(pendingRequest.id);
  });

  it("records ctx.actorId on the decision row's decidedByUserId", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pendingRequest], [], [{ ...pendingRequest, status: "CANCELLED" }]);

    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: pendingRequest.id, reason: "stuck" }, ctx),
    );

    const decisionRow = mock.inserts[0].insertValues();
    expect(decisionRow.decidedByUserId).toBe(ctx.actorId);
  });

  it("writes the supplied reason to the decision row's comment", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pendingRequest], [], [{ ...pendingRequest, status: "CANCELLED" }]);

    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: pendingRequest.id, reason: "requester left the company" }, ctx),
    );

    const decisionRow = mock.inserts[0].insertValues();
    expect(decisionRow.comment).toBe("requester left the company");
  });

  it("throws MISSING_REQUIRED_FIELD when reason is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pendingRequest]);

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

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

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

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: "nonexistent", reason: "stuck" }, ctx),
    );

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