import { APIClient, APIResponse, type AuthStoreType } from './base'

const BASE_URL = import.meta.env.VITE_API_URL + '/auth'

export interface User {
  id: number
  username: string
  createdAt: number
  isLocked: boolean
  isAdmin: boolean
}

export interface UserUpdatePayload {
  username?: string
  password?: string
  isLocked?: boolean
}

export class AuthenticationAPIClient extends APIClient {
  constructor(authStore: AuthStoreType) {
    super(BASE_URL, authStore)
  }

  login(username: string, password: string): APIResponse<User> {
    const promise = fetch(this.baseUrl + '/login', {
      method: 'POST',
      headers: {
        Authorization: 'Basic ' + btoa(username + ':' + password),
      },
    })
    return new APIResponse(this.handleAPIResponse(promise))
  }

  getUsers(page: number = 0, pageSize: number = 30): APIResponse<User[]> {
    return super.get(`/admin/users?page=${page}&size=${pageSize}`)
  }

  deleteUser(userId: number): APIResponse<void> {
    return super.delete(`/admin/users/${userId}`)
  }

  updateUser(userId: number, payload: UserUpdatePayload): APIResponse<User> {
    return super.put(`/admin/users/${userId}`, payload)
  }

  createUser(username: string, password: string): APIResponse<User> {
    return super.post(`/admin/users/`, { username: username, password: password })
  }
}
