import apiClient from './client'
import { UserRoleValue } from './users'

export interface LoginRequest {
  username: string
  password: string
}

export interface TokenResponse {
  access_token: string
  refresh_token: string
  token_type?: string
  password_change_required?: boolean
}

export interface PasswordChangeRequest {
  current_password: string
  new_password: string
}

export interface PasswordChangeResponse {
  success: boolean
  message: string
}

export interface UserResponse {
  username: string
  is_admin?: boolean
  role?: UserRoleValue
  permissions?: Record<string, boolean>
}

export const authApi = {
  login: async (credentials: LoginRequest): Promise<TokenResponse> => {
    const { data } = await apiClient.post<TokenResponse>(
      '/api/v1/auth/login',
      credentials
    )
    return data
  },

  refresh: async (refreshToken: string): Promise<TokenResponse> => {
    const { data } = await apiClient.post<TokenResponse>(
      '/api/v1/auth/refresh',
      { refresh_token: refreshToken }
    )
    return data
  },

  me: async (): Promise<UserResponse> => {
    const { data } = await apiClient.get<UserResponse>('/api/v1/auth/me')
    return data
  },

  changePassword: async (
    request: PasswordChangeRequest
  ): Promise<PasswordChangeResponse> => {
    const { data } = await apiClient.post<PasswordChangeResponse>(
      '/api/v1/auth/change-password',
      request
    )
    return data
  },
}

