import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import { PermissionNotFoundError, RoleNotFoundError } from "../lib/errors.generated";
import { basePermission, baseRole, baseRolePermission } from "../testing/fixtures";
import { run } from "./assignPermissionToRole";

describe("assignPermissionToRole", () => {
  it("throws when role does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, {
      roleId: "nonexistent-role",
      permissionId: basePermission.id,
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(RoleNotFoundError);
    }
  });

  it("throws when permission does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseRole) // Role found
      .mockReturnValueOnce(undefined); // Permission not found

    const result = await run(db, {
      roleId: baseRole.id,
      permissionId: "nonexistent-permission",
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(PermissionNotFoundError);
    }
  });

  it("returns success when assignment already exists (idempotent)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseRole) // Role found
      .mockReturnValueOnce(basePermission) // Permission found
      .mockReturnValueOnce(baseRolePermission); // Assignment already exists

    const result = await run(db, {
      roleId: baseRole.id,
      permissionId: basePermission.id,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.rolePermission).toEqual(baseRolePermission);
    }
    expect(spies.insert).not.toHaveBeenCalled();
  });

  it("creates RolePermission", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const newRolePermission = {
      ...baseRolePermission,
      id: "new-role-permission-id",
    };

    spies.select
      .mockReturnValueOnce(baseRole) // Role found
      .mockReturnValueOnce(basePermission) // Permission found
      .mockReturnValueOnce(undefined); // No existing assignment
    spies.insert.mockReturnValue(newRolePermission);

    const result = await run(db, {
      roleId: baseRole.id,
      permissionId: basePermission.id,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.rolePermission.roleId).toBe(baseRole.id);
      expect(result.value.rolePermission.permissionId).toBe(basePermission.id);
    }
    expect(spies.insert).toHaveBeenCalled();
  });
});
