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 {
  MissingRequiredFieldError,
  NotActiveAssigneeError,
  ParentRequestNotPendingError,
  SelfDecisionNotAllowedError,
} from "../lib/errors.generated";
import {
  approvedRequest,
  inProgressStep1,
  pendingAssigneeUser,
  pendingRequest,
} from "../testing/fixtures";
import { run } from "./rejectApprovalStep";

const requiredAssignee = { ...pendingAssigneeUser, required: true } as const;
const optionalAssignee = { ...pendingAssigneeUser, required: false } as const;

const validInput = {
  approvalStepAssigneeId: pendingAssigneeUser.id,
  reason: "Budget exceeded",
};

const actorCtx: CommandContext = {
  actorId: pendingAssigneeUser.userId!,
  permissions: [],
};

describe("rejectApprovalStep", () => {
  it("rejects a step from a required = true assignee and cascades the request to REJECTED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedRequest = {
      ...pendingRequest,
      status: "REJECTED" as const,
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    };
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce(undefined); // assignee update
    spies.update.mockReturnValueOnce(undefined); // step update
    spies.update.mockReturnValueOnce(updatedRequest); // request update returning

    const result = await run(db, validInput, actorCtx);

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

  it("rejects a step from a required = false (optional) assignee and cascades the request to REJECTED immediately, regardless of remaining assignees", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedRequest = {
      ...pendingRequest,
      status: "REJECTED" as const,
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    };
    spies.select.mockReturnValueOnce(optionalAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(updatedRequest);

    const result = await run(db, validInput, actorCtx);

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

  it("writes the reason verbatim to ApprovalDecision.comment and ApprovalRequest.rejectionReason in the same transaction", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce({
      ...pendingRequest,
      status: "REJECTED",
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    });

    await run(db, validInput, actorCtx);

    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ comment: validInput.reason }),
    );
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({
        status: "REJECTED",
        rejectionReason: validInput.reason,
      }),
    );
  });

  it("writes one ApprovalDecision row with decision = REJECT, both ids set", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce({
      ...pendingRequest,
      status: "REJECTED",
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    });

    await run(db, validInput, actorCtx);

    expect(spies.insert).toHaveBeenCalledTimes(1);
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({
        decision: "REJECT",
        approvalRequestId: pendingRequest.id,
        approvalStepId: inProgressStep1.id,
        decidedByUserId: actorCtx.actorId,
      }),
    );
  });

  it("transitions assignee, step, and request rows to REJECTED and stamps resolvedAt on each", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce({
      ...pendingRequest,
      status: "REJECTED",
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    });

    await run(db, validInput, actorCtx);

    // 3 updates: assignee, step, request
    expect(spies.update).toHaveBeenCalledTimes(3);
    const setCalls = spies.set.mock.calls.map((c): unknown => c[0]);
    expect(setCalls).toEqual([
      expect.objectContaining({
        status: "REJECTED",
        resolvedAt: expect.any(Date) as unknown as Date,
      }),
      expect.objectContaining({
        status: "REJECTED",
        resolvedAt: expect.any(Date) as unknown as Date,
      }),
      expect.objectContaining({
        status: "REJECTED",
        resolvedAt: expect.any(Date) as unknown as Date,
        rejectionReason: validInput.reason,
      }),
    ]);
  });

  it("leaves trailing steps in PENDING (no SKIPPED state) — never updates ApprovalStep with status PENDING", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(pendingRequest);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce({
      ...pendingRequest,
      status: "REJECTED",
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    });

    await run(db, validInput, actorCtx);

    const setCalls = spies.set.mock.calls.map((c) => c[0] as { status?: string });
    expect(setCalls.every((s) => s.status !== "PENDING")).toBe(true);
    expect(setCalls.every((s) => s.status !== "SKIPPED")).toBe(true);
  });

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

    const result = await run(
      db,
      { approvalStepAssigneeId: pendingAssigneeUser.id, reason: "   " },
      actorCtx,
    );

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

  it("throws NOT_ACTIVE_ASSIGNEE when the assignee row is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, validInput, actorCtx);

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

  it("throws NOT_ACTIVE_ASSIGNEE when the actor does not own the assignee", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);

    const result = await run(db, validInput, {
      actorId: "different-user",
      permissions: [],
    });

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

  it("throws NOT_ACTIVE_ASSIGNEE when the assignee status is not PENDING", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...requiredAssignee, status: "APPROVED" });

    const result = await run(db, validInput, actorCtx);

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

  it("throws NOT_ACTIVE_ASSIGNEE when the parent step is not IN_PROGRESS", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce({ ...inProgressStep1, status: "PENDING" });

    const result = await run(db, validInput, actorCtx);

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

  it("throws PARENT_REQUEST_NOT_PENDING when the parent request is in any non-PENDING status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(approvedRequest);

    const result = await run(db, validInput, actorCtx);

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

  it("throws SELF_DECISION_NOT_ALLOWED when the actor is the requester", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // assignee.userId must equal ctx.actorId; ctx.actorId must equal request.requesterId
    const selfAssignee = {
      ...requiredAssignee,
      userId: pendingRequest.requesterId,
    };
    spies.select.mockReturnValueOnce(selfAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(pendingRequest);

    const result = await run(db, validInput, {
      actorId: pendingRequest.requesterId,
      permissions: [],
    });

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

  it("a reject blocked by SoD or parent-Request liveness writes nothing and does not cascade", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(requiredAssignee);
    spies.select.mockReturnValueOnce(inProgressStep1);
    spies.select.mockReturnValueOnce(approvedRequest); // parent-Request liveness fails

    const result = await run(db, validInput, actorCtx);

    expect(result.ok).toBe(false);
    expect(spies.insert).not.toHaveBeenCalled();
    expect(spies.update).not.toHaveBeenCalled();
    expect(spies.values).not.toHaveBeenCalled();
    expect(spies.set).not.toHaveBeenCalled();
  });
});
