import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  InvalidStatusTransitionError,
  RoleHasActiveAssignmentsError,
  RoleNotFoundError,
} from "../lib/errors.generated";
import { baseRole, inactiveRole, baseUserRole } from "../testing/fixtures";
import { run } from "./deactivateRole";

describe("deactivateRole", () => {
  it("throws when role does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { roleId: "nonexistent-role" }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(RoleNotFoundError);
    }
  });

  it("throws when role is already INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveRole]);

    const result = await mock.withTx((trx) => run(trx, { roleId: inactiveRole.id }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusTransitionError);
    }
  });

  it("throws when role has active user assignments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseRole],
      // UserRole query returns active assignments
      [baseUserRole],
    );

    const result = await mock.withTx((trx) => run(trx, { roleId: baseRole.id }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(RoleHasActiveAssignmentsError);
    }
  });

  it("deactivates ACTIVE role with no assignments to INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedRole = {
      ...baseRole,
      status: "INACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    mock.enqueueResults(
      [baseRole],
      // No active UserRole assignments
      [],
      [deactivatedRole],
      // recomputePermissionsForUsersWithRole: query UserRole by roleId
      [],
    );

    const result = await mock.withTx((trx) => run(trx, { roleId: baseRole.id }));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.role.status).toBe("INACTIVE");
      expect(result.value.role.updatedAt).not.toBeNull();
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("triggers recomputation of effective permissions", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedRole = {
      ...baseRole,
      status: "INACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };
    const updatedUser = {
      id: "user-active-1",
      permissions: [],
    };

    mock.enqueueResults(
      [baseRole],
      // No active UserRole assignments
      [],
      [deactivatedRole],
      // recomputePermissionsForUsersWithRole: query UserRole by roleId returns one user
      [{ userId: "user-active-1" }],
      // recomputeUserPermissions: query permission keys for that user
      [],
      // recomputeUserPermissions: update user permissions
      [updatedUser],
    );

    const result = await mock.withTx((trx) => run(trx, { roleId: baseRole.id }));

    expect(result.ok).toBe(true);
    // Role update + user permission recompute update
    expect(mock.updates).toHaveLength(2);
  });
});
