import { api, type ApiEnvelope, unwrapApiData } from '@/lib/api'

export type PageResult<T> = {
  list: T[]
  total: number
  page: number
  pageSize: number
}

export type AdminRole = {
  code: string
  name: string
}

export type AdminUser = {
  id: string
  name: string
  email: string
  enabled: boolean
  parentId: string | null
  parentPath: string | null
  mustChangePassword: boolean
  roles: AdminRole[]
  roleCode?: string
  roleName?: string
  lastLoginAt: string | null
  createdAt: string
  updatedAt: string
}

export type PermissionResource = {
  resource: string
  name: string
  actions: string[]
}

export type PermissionRole = AdminRole & {
  permissions: Record<string, string[]>
}

export type PermissionConfig = {
  resources: PermissionResource[]
  roles: PermissionRole[]
}

export type UserPermissionDetail = {
  resources: PermissionResource[]
  rolePermissions: Record<string, string[]>
  customPermissions: Record<string, string[]> | null
  effectivePermissions: Record<string, string[]>
  isCustom: boolean
  canEdit: boolean
}

export type AuditLog = {
  id: string
  actorId: string | null
  actorUsername: string | null
  action: string
  resourceType: string | null
  resourceId: string | null
  metadata: Record<string, unknown> | null
  ipAddress: string | null
  createdAt: string
}

export function listAdminUsers(params: {
  page: number
  pageSize: number
  keyword?: string
}) {
  return api
    .get<PageResult<AdminUser> | ApiEnvelope<PageResult<AdminUser>>>(
      '/api/admin/users',
      { params }
    )
    .then((response) => unwrapApiData(response.data))
}

export function listAdminRoles() {
  return api
    .get<AdminRole[] | ApiEnvelope<AdminRole[]>>('/api/admin/roles')
    .then((response) => unwrapApiData(response.data))
}

export function createAdminUser(data: {
  name: string
  email: string
  password: string
  roleCode: string
  mustChangePassword: boolean
}) {
  return api
    .post<AdminUser | ApiEnvelope<AdminUser>>('/api/admin/users', data)
    .then((response) => unwrapApiData(response.data))
}

export function updateAdminUserEnabled(id: string, enabled: boolean) {
  return api
    .patch<AdminUser | ApiEnvelope<AdminUser>>(
      `/api/admin/users/${id}/enabled`,
      { enabled }
    )
    .then((response) => unwrapApiData(response.data))
}

export function updateAdminUser(
  id: string,
  data: {
    name: string
    email: string
    roleCode: string
    enabled: boolean
    mustChangePassword: boolean
  }
) {
  return api
    .patch<AdminUser | ApiEnvelope<AdminUser>>(`/api/admin/users/${id}`, data)
    .then((response) => unwrapApiData(response.data))
}

export function updateAdminUserRole(id: string, roleCode: string) {
  return api
    .patch<AdminUser | ApiEnvelope<AdminUser>>(
      `/api/admin/users/${id}/role`,
      { roleCode }
    )
    .then((response) => unwrapApiData(response.data))
}

export function listPermissions() {
  return api
    .get<PermissionConfig | ApiEnvelope<PermissionConfig>>(
      '/api/admin/permissions'
    )
    .then((response) => unwrapApiData(response.data))
}

export function updateRolePermissions(
  roleCode: string,
  permissions: Record<string, string[]>
) {
  return api
    .patch<PermissionRole | ApiEnvelope<PermissionRole>>(
      `/api/admin/permissions/roles/${roleCode}`,
      {
        permissions,
      }
    )
    .then((response) => unwrapApiData(response.data))
}

export function getUserPermissions(id: string) {
  return api
    .get<UserPermissionDetail | ApiEnvelope<UserPermissionDetail>>(
      `/api/admin/users/${id}/permissions`
    )
    .then((response) => unwrapApiData(response.data))
}

export function updateUserPermissions(
  id: string,
  permissions: Record<string, string[]>
) {
  return api
    .patch<UserPermissionDetail | ApiEnvelope<UserPermissionDetail>>(
      `/api/admin/users/${id}/permissions`,
      { permissions }
    )
    .then((response) => unwrapApiData(response.data))
}

export function resetUserPermissions(id: string) {
  return api
    .delete<UserPermissionDetail | ApiEnvelope<UserPermissionDetail>>(
      `/api/admin/users/${id}/permissions`
    )
    .then((response) => unwrapApiData(response.data))
}

export function listAuditLogs(params: {
  page: number
  pageSize: number
  actorUsername?: string
  action?: string
  loginResult?: string
}) {
  return api
    .get<PageResult<AuditLog> | ApiEnvelope<PageResult<AuditLog>>>(
      '/api/admin/audit-logs',
      { params }
    )
    .then((response) => unwrapApiData(response.data))
}
