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 {
  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 mock = createKyselyMock<Namespace["main-db"]>();
    const updatedRequest = {
      ...pendingRequest,
      status: "REJECTED" as const,
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    };
    mock.enqueueResults(
      [requiredAssignee],
      [inProgressStep1],
      [pendingRequest],
      [],
      [],
      [],
      [updatedRequest],
    );

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    const updatedRequest = {
      ...pendingRequest,
      status: "REJECTED" as const,
      rejectionReason: validInput.reason,
      resolvedAt: new Date(),
      updatedAt: new Date(),
    };
    mock.enqueueResults(
      [optionalAssignee],
      [inProgressStep1],
      [pendingRequest],
      [],
      [],
      [],
      [updatedRequest],
    );

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [requiredAssignee],
      [inProgressStep1],
      [pendingRequest],
      [],
      [],
      [],
      [
        {
          ...pendingRequest,
          status: "REJECTED",
          rejectionReason: validInput.reason,
          resolvedAt: new Date(),
          updatedAt: new Date(),
        },
      ],
    );

    await mock.withTx((trx) => run(trx, validInput, actorCtx));

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ comment: validInput.reason }),
    );
    expect(mock.updates[2].updateValues()).toEqual(
      expect.objectContaining({
        status: "REJECTED",
        rejectionReason: validInput.reason,
      }),
    );
  });

  it("writes one ApprovalDecision row with decision = REJECT, both ids set", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [requiredAssignee],
      [inProgressStep1],
      [pendingRequest],
      [],
      [],
      [],
      [
        {
          ...pendingRequest,
          status: "REJECTED",
          rejectionReason: validInput.reason,
          resolvedAt: new Date(),
          updatedAt: new Date(),
        },
      ],
    );

    await mock.withTx((trx) => run(trx, validInput, actorCtx));

    expect(mock.inserts).toHaveLength(1);
    expect(mock.inserts[0].insertValues()).toEqual(
      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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [requiredAssignee],
      [inProgressStep1],
      [pendingRequest],
      [],
      [],
      [],
      [
        {
          ...pendingRequest,
          status: "REJECTED",
          rejectionReason: validInput.reason,
          resolvedAt: new Date(),
          updatedAt: new Date(),
        },
      ],
    );

    await mock.withTx((trx) => run(trx, validInput, actorCtx));

    // 3 updates: assignee, step, request
    expect(mock.updates).toHaveLength(3);
    const setCalls = mock.updates.map((u): unknown => u.updateValues());
    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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [requiredAssignee],
      [inProgressStep1],
      [pendingRequest],
      [],
      [],
      [],
      [
        {
          ...pendingRequest,
          status: "REJECTED",
          rejectionReason: validInput.reason,
          resolvedAt: new Date(),
          updatedAt: new Date(),
        },
      ],
    );

    await mock.withTx((trx) => run(trx, validInput, actorCtx));

    const setCalls = mock.updates.map((u) => u.updateValues() 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([requiredAssignee], [inProgressStep1], [pendingRequest]);

    const result = await mock.withTx((trx) =>
      run(trx, { approvalStepAssigneeId: pendingAssigneeUser.id, reason: "   " }, actorCtx),
    );

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

  it("throws NOT_ACTIVE_ASSIGNEE when the assignee row is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

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

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

  it("throws NOT_ACTIVE_ASSIGNEE when the assignee status is not PENDING", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...requiredAssignee, status: "APPROVED" }]);

    const result = await mock.withTx((trx) => run(trx, validInput, actorCtx));

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

  it("throws NOT_ACTIVE_ASSIGNEE when the parent step is not IN_PROGRESS", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([requiredAssignee], [{ ...inProgressStep1, status: "PENDING" }]);

    const result = await mock.withTx((trx) => run(trx, validInput, actorCtx));

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

  it("throws PARENT_REQUEST_NOT_PENDING when the parent request is in any non-PENDING status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([requiredAssignee], [inProgressStep1], [approvedRequest]);

    const result = await mock.withTx((trx) => run(trx, validInput, actorCtx));

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

  it("throws SELF_DECISION_NOT_ALLOWED when the actor is the requester", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // assignee.userId must equal ctx.actorId; ctx.actorId must equal request.requesterId
    const selfAssignee = {
      ...requiredAssignee,
      userId: pendingRequest.requesterId,
    };
    mock.enqueueResults([selfAssignee], [inProgressStep1], [pendingRequest]);

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

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

  it("a reject blocked by SoD or parent-Request liveness writes nothing and does not cascade", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([requiredAssignee], [inProgressStep1], [approvedRequest]); // parent-Request liveness fails

    const result = await mock.withTx((trx) => run(trx, validInput, actorCtx));

    expect(result.ok).toBe(false);
    expect(mock.inserts).toHaveLength(0);
    expect(mock.updates).toHaveLength(0);
  });
});
