import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  RoleNotActiveError,
  RoleNotFoundError,
  UserNotActiveError,
  UserNotFoundError,
} from "../lib/errors.generated";
import {
  activeUser,
  baseRole,
  baseUserRole,
  inactiveRole,
  inactiveUser,
  pendingUser,
} from "../testing/fixtures";
import { run } from "./assignRoleToUser";

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

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

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

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

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

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

  it("assigns role to PENDING user", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newUserRole = { ...baseUserRole, id: "new-user-role-id", userId: pendingUser.id };
    // PENDING users keep permissions [] until activation (User.status gate in recompute)
    const updatedUser = { ...pendingUser, permissions: [] };

    mock.enqueueResults(
      [pendingUser],
      [baseRole],
      [], // No existing assignment
      [newUserRole],
      [], // recompute: no rows because user is not ACTIVE
      [updatedUser],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.userRole.userId).toBe(pendingUser.id);
    }
    // The association is created, but recompute keeps permissions dormant ([])
    expect(mock.inserts.length).toBeGreaterThan(0);
    expect(mock.updates.at(-1)?.updateValues()).toEqual({ permissions: [] });
  });

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

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

  it("returns success when assignment already exists (idempotent)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedUser = { ...activeUser, permissions: ["orders:read"] };
    mock.enqueueResults(
      [activeUser],
      [baseRole],
      [baseUserRole], // Assignment exists
      [{ key: "orders:read" }], // Permission keys from recompute
      [updatedUser],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.userRole).toEqual(baseUserRole);
      expect(result.value.user.permissions).toEqual(["orders:read"]);
    }
    expect(mock.inserts).toHaveLength(0);
  });

  it("creates UserRole and recomputes permissions", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newUserRole = {
      ...baseUserRole,
      id: "new-user-role-id",
    };
    const updatedUser = { ...activeUser, permissions: ["orders:read"] };

    mock.enqueueResults(
      [activeUser],
      [baseRole],
      [], // No existing assignment
      [newUserRole],
      [{ key: "orders:read" }], // Permission keys from recompute
      [updatedUser],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.userRole.userId).toBe(activeUser.id);
      expect(result.value.userRole.roleId).toBe(baseRole.id);
      expect(result.value.user.permissions).toEqual(["orders:read"]);
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });
});
