import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidPermissionError,
  RoleNotActiveError,
  RoleNotFoundError,
} from "../lib/errors.generated";
import { baseRole, inactiveRole } from "../testing/fixtures";
import { run } from "./grantPermissionToRole";

describe("grantPermissionToRole", () => {
  it("throws when permission key format is invalid", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, {
      roleId: baseRole.id,
      permission: "1invalid",
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidPermissionError);
    }
  });

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

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

  it("throws when role is INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveRole);

    const result = await run(db, {
      roleId: inactiveRole.id,
      permission: "sales:salesOrder:create",
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(RoleNotActiveError);
    }
  });

  it("returns success when permission already exists in array (idempotent)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const roleWithPermission = {
      ...baseRole,
      permissions: ["sales:salesOrder:create"],
    };
    spies.select.mockReturnValueOnce(roleWithPermission);

    const result = await run(db, {
      roleId: baseRole.id,
      permission: "sales:salesOrder:create",
    });
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.role).toEqual(roleWithPermission);
    }
    expect(spies.update).not.toHaveBeenCalled();
  });

  it("adds permission key to role's permissions array", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedRole = {
      ...baseRole,
      permissions: ["sales:salesOrder:create"],
      updatedAt: new Date(),
    };
    spies.select.mockReturnValueOnce(baseRole);
    spies.update.mockReturnValue(updatedRole);

    const result = await run(db, {
      roleId: baseRole.id,
      permission: "sales:salesOrder:create",
    });
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.role.permissions).toContain("sales:salesOrder:create");
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
