import apiClient from './client'

export type UserRoleValue =
  | 'admin'
  | 'manager'
  | 'moderator'
  | 'reviewer'
  | 'editor'
  | 'importer'
  | 'viewer'

export interface UserResponse {
  id: number
  username: string
  email: string | null
  full_name: string | null
  is_active: boolean
  is_admin: boolean
  role?: UserRoleValue | null
  created_date: string
  last_login: string | null
}

export interface UserCreateRequest {
  username: string
  password: string
  email: string
  full_name: string
  is_active?: boolean
  is_admin?: boolean
  role: UserRoleValue
  give_frontend_permission?: boolean
}

export interface UserUpdateRequest {
  password?: string | null
  email: string
  full_name: string
  is_active?: boolean
  is_admin?: boolean
  role?: UserRoleValue
  give_frontend_permission?: boolean
}

export interface UsersListResponse {
  items: UserResponse[]
  total: number
}

export const usersApi = {
  listUsers: async (params?: {
    is_active?: boolean
    is_admin?: boolean
  }): Promise<UsersListResponse> => {
    const { data } = await apiClient.get<UsersListResponse>('/api/v1/users', {
      params,
    })
    return data
  },

  getUser: async (userId: number): Promise<UserResponse> => {
    const { data } = await apiClient.get<UserResponse>(`/api/v1/users/${userId}`)
    return data
  },

  createUser: async (request: UserCreateRequest): Promise<UserResponse> => {
    const { data } = await apiClient.post<UserResponse>('/api/v1/users', request)
    return data
  },

  updateUser: async (
    userId: number,
    request: UserUpdateRequest
  ): Promise<UserResponse> => {
    const { data } = await apiClient.put<UserResponse>(
      `/api/v1/users/${userId}`,
      request
    )
    return data
  },

  deleteUser: async (userId: number): Promise<{ message?: string; deactivated?: boolean }> => {
    const response = await apiClient.delete(`/api/v1/users/${userId}`)
    // Return data if present (200 OK with deactivation message), otherwise empty object (204 No Content)
    return response.data || {}
  },
}

