import { api } from './http';

export interface MePermissions {
  uid: string;
  tenant_id: string;
  roles: string[];
  permissions: Record<string, string>;
}

export interface Role {
  id: string;
  key: string;
  display_name: string;
  status: string;
  is_system: boolean;
}

export interface RoleList {
  roles: Role[];
}

export interface UserRoleList {
  user_roles: Array<{
    role_id: string;
    role_key: string;
    role_display_name?: string;
    display_name?: string;
  }>;
}

export interface PermissionNode {
  id: string;
  parent?: string;
  name: string;
  http_methods?: string;
  http_path?: string;
  status: string;
  type: string;
  children?: PermissionNode[];
}

export interface PermissionCatalog {
  tree?: PermissionNode[];
  list?: PermissionNode[];
}

export interface RolePermissions {
  permissions: PermissionNode[];
}

const ADMIN_ROLES = new Set(['tenant_admin', 'tenant_owner']);

export function isAdminRole(roles: string[]) {
  return roles.some((r) => ADMIN_ROLES.has(r));
}

export function getMyPermissions() {
  return api<MePermissions>('/api/v1/permissions/me');
}

export function listRoles() {
  return api<RoleList>('/api/v1/permissions/roles');
}

export function createRole(key: string, displayName: string) {
  return api<Role>('/api/v1/permissions/roles', {
    method: 'POST',
    body: JSON.stringify({ key, display_name: displayName, status: 'open' }),
  });
}

export function updateRole(id: string, displayName: string) {
  return api<Role>(`/api/v1/permissions/roles/${id}`, {
    method: 'PATCH',
    body: JSON.stringify({ display_name: displayName }),
  });
}

export function deleteRole(id: string) {
  return api(`/api/v1/permissions/roles/${id}`, { method: 'DELETE' });
}

export function listUserRoles(uid: string) {
  return api<UserRoleList>(`/api/v1/permissions/users/${uid}/roles`);
}

export function assignUserRole(uid: string, roleId: string) {
  return api(`/api/v1/permissions/users/${uid}/roles`, {
    method: 'POST',
    body: JSON.stringify({ role_id: roleId, source: 'manual' }),
  });
}

export function revokeUserRole(uid: string, roleId: string) {
  return api(`/api/v1/permissions/users/${uid}/roles/${roleId}`, {
    method: 'DELETE',
  });
}

export function reloadPolicy(tenantId: string) {
  return api('/api/v1/permissions/policy/reload', {
    method: 'POST',
    body: JSON.stringify({ tenant_id: tenantId }),
  });
}

export function getPermissionCatalog(opts?: { tree?: boolean; type?: string }) {
  const q = new URLSearchParams();
  if (opts?.tree) q.set('tree', 'true');
  if (opts?.type) q.set('type', opts.type);
  const qs = q.toString();
  return api<PermissionCatalog>(
    `/api/v1/permissions/catalog${qs ? `?${qs}` : ''}`,
  );
}

export function getRolePermissions(roleId: string) {
  return api<RolePermissions>(`/api/v1/permissions/roles/${roleId}/permissions`);
}

export function replaceRolePermissions(roleId: string, permissionIds: string[]) {
  return api(`/api/v1/permissions/roles/${roleId}/permissions`, {
    method: 'PUT',
    body: JSON.stringify({ permission_ids: permissionIds }),
  });
}
