import { Transaction } from "../generated/kysely-tailordb";
import { PermissionNotFoundError, RoleNotFoundError } from "../lib/errors.generated";
import { ok, err } from "@tailor-platform/erp-kit/module";

export interface AssignPermissionToRoleInput {
  roleId: string;
  permissionId: string;
}

/**
 * Function: assignPermissionToRole
 *
 * Assigns a permission to a role. Operation is idempotent - assigning
 * the same permission twice does not create duplicate records or error.
 *
 * Note: Permissions for affected users are recomputed asynchronously via executor.
 */
export async function run(db: Transaction, input: AssignPermissionToRoleInput) {
  const role = await db
    .selectFrom("Role")
    .selectAll()
    .where("id", "=", input.roleId)
    .executeTakeFirst();

  if (!role) {
    return err(new RoleNotFoundError(input.roleId));
  }

  const permission = await db
    .selectFrom("Permission")
    .selectAll()
    .where("id", "=", input.permissionId)
    .executeTakeFirst();

  if (!permission) {
    return err(new PermissionNotFoundError(input.permissionId));
  }

  // Idempotent: return existing assignment without creating duplicates
  const existingAssignment = await db
    .selectFrom("RolePermission")
    .selectAll()
    .where("roleId", "=", input.roleId)
    .where("permissionId", "=", input.permissionId)
    .forUpdate()
    .executeTakeFirst();

  if (existingAssignment) {
    return ok({ rolePermission: existingAssignment });
  }

  // Permission recomputation for affected users is handled asynchronously by executor
  const rolePermission = await db
    .insertInto("RolePermission")
    .values({
      roleId: input.roleId,
      permissionId: input.permissionId,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

  return ok({ rolePermission: rolePermission! });
}
