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 "./resubmitApprovalRequest";

describe("resubmitApprovalRequest", () => {
  const requesterCtx: CommandContext = {
    actorId: revisionRequestedRequest.requesterId,
    permissions: [],
  };

  // Happy-path result queue, one entry per statement in run().
  function enqueueResubmit(mock: ReturnType<typeof createKyselyMock<Namespace["main-db"]>>) {
    mock.enqueueResults(
      [revisionRequestedRequest], // load request (forUpdate)
      [{}], // insert decision
      [
        { id: "step-a", stepOrder: 1 },
        { id: "step-b", stepOrder: 2 },
      ], // load steps
      [], // reset all steps
      [], // reset approved assignees
      [], // re-activate first step
      [{ ...revisionRequestedRequest, status: "PENDING" as const }], // update request, returningAll
    );
  }

  it("transitions REVISION_REQUESTED to PENDING and writes a RESUBMIT decision", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    enqueueResubmit(mock);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.approvalRequest.status).toBe("PENDING");
    }
    expect(mock.inserts.length).toBe(1);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        decision: "RESUBMIT",
        approvalRequestId: revisionRequestedRequest.id,
        decidedByUserId: requesterCtx.actorId,
      }),
    );
  });

  it("resets every step to PENDING, resets approved assignees, re-activates the first step, and sets the request PENDING", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    enqueueResubmit(mock);

    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: revisionRequestedRequest.id }, requesterCtx),
    );

    const setCalls = mock.updates.map((u): unknown => u.updateValues());
    expect(setCalls).toEqual([
      { status: "PENDING", resolvedAt: null }, // reset all steps
      { status: "PENDING", resolvedAt: null }, // reset approved assignees
      { status: "IN_PROGRESS" }, // re-activate the lowest-stepOrder step
      { status: "PENDING" }, // request back to PENDING
    ]);
  });

  it("does not reset DELEGATED assignees — the delegatee row remains the seat's only voter", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    enqueueResubmit(mock);

    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: revisionRequestedRequest.id }, requesterCtx),
    );

    // The assignee reset must not revive DELEGATED delegators alongside their delegatee.
    expect(mock.updates[1].parameters).toContain("APPROVED");
    expect(mock.updates[1].parameters).not.toContain("DELEGATED");
  });

  it("re-activates the lowest-stepOrder step", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    enqueueResubmit(mock);

    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: revisionRequestedRequest.id }, requesterCtx),
    );

    // The third update activates the first step; its where clause targets step-a.
    expect(mock.updates[2].parameters).toContain("step-a");
  });

  it("accepts an optional comment and stores it on the decision row", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    enqueueResubmit(mock);

    await mock.withTx((trx) =>
      run(
        trx,
        {
          approvalRequestId: revisionRequestedRequest.id,
          comment: "Updated quantities per feedback",
        },
        requesterCtx,
      ),
    );

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ comment: "Updated quantities per feedback" }),
    );
  });

  it("does not delete or mutate any prior ApprovalDecision row", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    enqueueResubmit(mock);

    await mock.withTx((trx) =>
      run(trx, { approvalRequestId: revisionRequestedRequest.id }, requesterCtx),
    );

    expect(mock.deletes.length).toBe(0);
  });

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

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

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

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

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

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

  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 },
        {
          actorId: approvedRequest.requesterId,
          permissions: [],
        },
      ),
    );

    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 },
        {
          actorId: rejectedRequest.requesterId,
          permissions: [],
        },
      ),
    );

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

    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 },
        {
          actorId: withdrawnRequest.requesterId,
          permissions: [],
        },
      ),
    );

    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" }, requesterCtx),
    );

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