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

describe("withdrawApprovalRequest", () => {
  it("transitions PENDING to WITHDRAWN and stamps resolvedAt", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = {
      ...pendingRequest,
      status: "WITHDRAWN" as const,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    };
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce(updated);

    const ctx: CommandContext = {
      actorId: pendingRequest.requesterId,
      permissions: [],
    };
    const result = await run(db, { 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(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({
        status: "WITHDRAWN",
        resolvedAt: expect.any(Date) as unknown as Date,
      }),
    );
  });

  it("writes an ApprovalDecision row with decision = WITHDRAW, approvalStepId null, and approvalRequestId set", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce({
      ...pendingRequest,
      status: "WITHDRAWN",
      resolvedAt: new Date(),
      updatedAt: new Date(),
    });

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

    expect(spies.insert).toHaveBeenCalledTimes(1);
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({
        approvalRequestId: pendingRequest.id,
        decision: "WITHDRAW",
      }),
    );
  });

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

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

    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ decidedByUserId: pendingRequest.requesterId }),
    );
  });

  it("accepts an optional comment and stores it on the decision row when supplied", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce({
      ...pendingRequest,
      status: "WITHDRAWN",
      resolvedAt: new Date(),
      updatedAt: new Date(),
    });

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

    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ comment: "Changing my mind" }),
    );
  });

  it("throws NOT_REQUESTER when called by a non-requester user", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(pendingRequest);

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NotRequesterError);
    }
    expect(spies.insert).not.toHaveBeenCalled();
    expect(spies.update).not.toHaveBeenCalled();
  });

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

    const ctx: CommandContext = {
      actorId: approvedRequest.requesterId,
      permissions: [],
    };
    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(rejectedRequest);

    const ctx: CommandContext = {
      actorId: rejectedRequest.requesterId,
      permissions: [],
    };
    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(cancelledRequest);

    const ctx: CommandContext = {
      actorId: cancelledRequest.requesterId,
      permissions: [],
    };
    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(withdrawnRequest);

    const ctx: CommandContext = {
      actorId: withdrawnRequest.requesterId,
      permissions: [],
    };
    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const ctx: CommandContext = {
      actorId: "test-actor",
      permissions: [],
    };
    const result = await run(db, { approvalRequestId: "nonexistent" }, ctx);

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