/**
 * Authentication Service
 * Handles OTP-based authentication with the backend
 */

import { apiClient } from '../client'

export interface RequestOTPRequest {
  phone_number: string
}

export interface RequestOTPResponse {
  code: number
  msg: string
  token: string
}

export interface VerifyOTPRequest {
  token: string
  otp_code: string
}

export interface AuthUser {
  id: number
  username: string
  email: string
  first_name: string
  last_name: string
  phone_number: string
}

export interface VerifyOTPResponse {
  code: number
  msg: string
  data: AuthUser
  token: string
}

export interface UpdateProfilePayload {
  first_name: string
  last_name: string
  email: string
}

export interface UpdateProfileResponse {
  code: number
  msg: string
  data: AuthUser
}

export const authService = {
  /**
   * Request OTP for phone number authentication
   */
  async requestOTP(phoneNumber: string): Promise<RequestOTPResponse> {
    return apiClient.post<RequestOTPResponse>('/api/auth/request-otp/', {
      phone_number: phoneNumber
    })
  },

  /**
   * Verify OTP code and get JWT token
   */
  async verifyOTP(token: string, otpCode: string): Promise<VerifyOTPResponse> {
    const response = await apiClient.post<VerifyOTPResponse>('/api/auth/verify-otp/', {
      token,
      otp_code: otpCode
    })

    if ( response.token) {
      apiClient.setAuthToken(response.token)
    }

    return response
  },

  /**
   * Update user profile (first name, last name, email)
   */
  async updateProfile(payload: UpdateProfilePayload): Promise<UpdateProfileResponse> {
    const response = await apiClient.patch<UpdateProfileResponse>('/users/me', payload)
    if (response.code !== 200 || !response.data) {
      throw new Error(response.msg || 'Failed to update profile')
    }
    return response
  },

  /**
   * Logout - clear authentication token
   */
  logout(): void {
    apiClient.clearAuthToken()
  }
}

