import client from './client';
import type { PaginatedResponse } from './types';

export interface RoleInfo {
  id: string;
  name: string;
  code: string;
  description?: string;
  is_system: boolean;
  version: number;
}

export interface PermissionInfo {
  id: string;
  code: string;
  name: string;
  resource: string;
  action: string;
  description?: string;
}

export interface CreateRoleRequest {
  name: string;
  code: string;
  description?: string;
}

export interface UpdateRoleRequest {
  name?: string;
  description?: string;
  version: number;
}

export async function listRoles(page = 1, pageSize = 20) {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<RoleInfo> }>(
    '/roles',
    { params: { page, page_size: pageSize } },
  );
  return data.data;
}

export async function getRole(id: string) {
  const { data } = await client.get<{ success: boolean; data: RoleInfo }>(`/roles/${id}`);
  return data.data;
}

export async function createRole(req: CreateRoleRequest) {
  const { data } = await client.post<{ success: boolean; data: RoleInfo }>('/roles', req);
  return data.data;
}

export async function updateRole(id: string, req: UpdateRoleRequest) {
  const { data } = await client.put<{ success: boolean; data: RoleInfo }>(`/roles/${id}`, req);
  return data.data;
}

export async function deleteRole(id: string) {
  await client.delete(`/roles/${id}`);
}

export async function assignPermissions(roleId: string, permissionIds: string[]) {
  await client.post(`/roles/${roleId}/permissions`, { permission_ids: permissionIds });
}

export async function getRolePermissions(roleId: string) {
  const { data } = await client.get<{ success: boolean; data: PermissionInfo[] }>(
    `/roles/${roleId}/permissions`,
  );
  return data.data;
}

export async function listPermissions() {
  const { data } = await client.get<{ success: boolean; data: PermissionInfo[] }>('/permissions');
  return data.data;
}
