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

describe("withdrawApprovalRequest", () => {
  it("transitions PENDING to WITHDRAWN and stamps resolvedAt", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = {
      ...pendingRequest,
      status: "WITHDRAWN" as const,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    };
    mock.enqueueResults([pendingRequest], [], [updated]);

    const ctx: CommandContext = {
      actorId: pendingRequest.requesterId,
      permissions: [],
    };
    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: pendingRequest.id }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest.status).toBe("WITHDRAWN");
      expect(result.value.approvalRequest.resolvedAt).toBeInstanceOf(Date);
    }
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({
        status: "WITHDRAWN",
        resolvedAt: expect.any(Date) as unknown as Date,
      }),
    );
  });

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

    const ctx: CommandContext = {
      actorId: revisionRequestedRequest.requesterId,
      permissions: [],
    };
    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: revisionRequestedRequest.id }, ctx),
    );

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

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

    const ctx: CommandContext = {
      actorId: pendingRequest.requesterId,
      permissions: [],
    };
    await mock.withTx((trx) => run(trx, { approvalRequestId: pendingRequest.id }, ctx));

    expect(mock.inserts).toHaveLength(1);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        approvalRequestId: pendingRequest.id,
        decision: "WITHDRAW",
      }),
    );
  });

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

    const ctx: CommandContext = {
      actorId: pendingRequest.requesterId,
      permissions: [],
    };
    await mock.withTx((trx) => run(trx, { approvalRequestId: pendingRequest.id }, ctx));

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ decidedByUserId: pendingRequest.requesterId }),
    );
  });

  it("accepts an optional comment and stores it on the decision row when supplied", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [pendingRequest],
      [],
      [
        {
          ...pendingRequest,
          status: "WITHDRAWN",
          resolvedAt: new Date(),
          updatedAt: new Date(),
        },
      ],
    );

    const ctx: CommandContext = {
      actorId: pendingRequest.requesterId,
      permissions: [],
    };
    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: pendingRequest.id, comment: "Changing my mind" }, ctx),
    );

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ comment: "Changing my mind" }),
    );
  });

  it("throws NOT_REQUESTER when called by a non-requester user", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pendingRequest]);

    const ctx: CommandContext = {
      actorId: "different-user",
      permissions: [],
    };
    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: pendingRequest.id }, ctx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NotRequesterError);
    }
    expect(mock.inserts).toHaveLength(0);
    expect(mock.updates).toHaveLength(0);
  });

  it("throws INVALID_STATUS_TRANSITION when the request is APPROVED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([approvedRequest]);

    const ctx: CommandContext = {
      actorId: approvedRequest.requesterId,
      permissions: [],
    };
    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: approvedRequest.id }, 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 ctx: CommandContext = {
      actorId: rejectedRequest.requesterId,
      permissions: [],
    };
    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: rejectedRequest.id }, ctx),
    );

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

  it("throws INVALID_STATUS_TRANSITION when the request is CANCELLED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([cancelledRequest]);

    const ctx: CommandContext = {
      actorId: cancelledRequest.requesterId,
      permissions: [],
    };
    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: cancelledRequest.id }, ctx),
    );

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

  it("throws INVALID_STATUS_TRANSITION when the request is already WITHDRAWN", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([withdrawnRequest]);

    const ctx: CommandContext = {
      actorId: withdrawnRequest.requesterId,
      permissions: [],
    };
    const result = await mock.withTx((trx) =>
      run(trx, { approvalRequestId: withdrawnRequest.id }, 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 ctx: CommandContext = {
      actorId: "test-actor",
      permissions: [],
    };
    const result = await mock.withTx((trx) => run(trx, { approvalRequestId: "nonexistent" }, ctx));

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