/**
 * Roles & Permissions Service
 * Handles roles and permissions-related API calls (Admin only)
 */

import { apiClient } from '../client'

export interface Role {
  id: string
  name: string
  totalUsers: number
  avatars: string[]
  description: string
  permissions?: string[]
}

export interface RoleStats {
  administrator: number
  author: number
  editor: number
  maintainer: number
  subscriber: number
}

export interface GetRolesResponse {
  roles: Role[]
  roleStats: RoleStats
}

export interface RoleUser {
  id: number
  fullName: string
  username: string
  email: string
  avatar: string
  role: string
  status: string
}

export interface GetRoleUsersResponse {
  users: RoleUser[]
}

export interface CreateRoleRequest {
  name: string
  description: string
  permissions: string[]
}

export interface CreateRoleResponse {
  role: Role
}

export interface UpdateRoleRequest {
  name?: string
  description?: string
  permissions?: string[]
}

export interface UpdateRoleResponse {
  role: Role
}

export interface DeleteRoleResponse {
  success: boolean
}

export interface Permission {
  id: number
  name: string
  createdDate: string // ISO 8601
  assignedTo: string | string[]
}

export interface GetPermissionsParams {
  search?: string
}

export interface GetPermissionsResponse {
  permissions: Permission[]
  total: number
}

export interface CreatePermissionRequest {
  name: string
  assignedTo: string | string[]
}

export interface CreatePermissionResponse {
  permission: Permission
}

export interface UpdatePermissionRequest {
  name?: string
  assignedTo?: string | string[]
}

export interface UpdatePermissionResponse {
  permission: Permission
}

export interface DeletePermissionResponse {
  success: boolean
}

export const rolesPermissionsService = {
  /**
   * دریافت لیست نقش‌ها
   */
  async getRoles(): Promise<{ roles: Role[]; roleStats: RoleStats }> {
    const response = await apiClient.get<GetRolesResponse>('/api/admin/roles')
    return {
      roles: response.roles || [],
      roleStats: response.roleStats
    }
  },

  /**
   * دریافت کاربران بر اساس نقش
   */
  async getRoleUsers(roleName: string): Promise<RoleUser[]> {
    const response = await apiClient.get<GetRoleUsersResponse>(`/api/admin/roles/${roleName}/users`)
    return response.users || []
  },

  /**
   * ایجاد نقش جدید
   */
  async createRole(data: CreateRoleRequest): Promise<Role> {
    const response = await apiClient.post<CreateRoleResponse>('/api/admin/roles', data)
    return response.role
  },

  /**
   * به‌روزرسانی نقش
   */
  async updateRole(roleId: string, data: UpdateRoleRequest): Promise<Role> {
    const response = await apiClient.put<UpdateRoleResponse>(`/api/admin/roles/${roleId}`, data)
    return response.role
  },

  /**
   * حذف نقش
   */
  async deleteRole(roleId: string): Promise<boolean> {
    const response = await apiClient.delete<DeleteRoleResponse>(`/api/admin/roles/${roleId}`)
    return response.success
  },

  /**
   * دریافت لیست Permission ها
   */
  async getPermissions(params?: GetPermissionsParams): Promise<{ permissions: Permission[]; total: number }> {
    const queryParams = new URLSearchParams()
    if (params?.search) queryParams.append('search', params.search)

    const queryString = queryParams.toString()
    const endpoint = `/api/admin/permissions${queryString ? `?${queryString}` : ''}`

    const response = await apiClient.get<GetPermissionsResponse>(endpoint)
    return {
      permissions: response.permissions || [],
      total: response.total || 0
    }
  },

  /**
   * ایجاد Permission جدید
   */
  async createPermission(data: CreatePermissionRequest): Promise<Permission> {
    const response = await apiClient.post<CreatePermissionResponse>('/api/admin/permissions', data)
    return response.permission
  },

  /**
   * به‌روزرسانی Permission
   */
  async updatePermission(permissionId: number, data: UpdatePermissionRequest): Promise<Permission> {
    const response = await apiClient.put<UpdatePermissionResponse>(`/api/admin/permissions/${permissionId}`, data)
    return response.permission
  },

  /**
   * حذف Permission
   */
  async deletePermission(permissionId: number): Promise<boolean> {
    const response = await apiClient.delete<DeletePermissionResponse>(`/api/admin/permissions/${permissionId}`)
    return response.success
  }
}




