import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveRole]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    const roleWithPermission = {
      ...baseRole,
      permissions: ["sales:salesOrder:create"],
    };
    mock.enqueueResults([roleWithPermission]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        roleId: baseRole.id,
        permission: "sales:salesOrder:create",
      }),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.role).toEqual(roleWithPermission);
    }
    expect(mock.updates).toHaveLength(0);
  });

  it("adds permission key to role's permissions array", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedRole = {
      ...baseRole,
      permissions: ["sales:salesOrder:create"],
      updatedAt: new Date(),
    };
    mock.enqueueResults([baseRole], [updatedRole]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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(mock.updates.length).toBeGreaterThan(0);
  });
});
