import { api } from '@/services/api'

export interface User {
  id: number
  name: string
  email: string
  email_verified_at: string | null
  is_super_admin: boolean
}

export interface AuthPayload {
  email: string
  password: string
  device_name?: string
}

export interface RegisterPayload extends AuthPayload {
  name: string
  password_confirmation: string
}

export interface ForgotPasswordPayload {
  email: string
}

export interface ResetPasswordPayload {
  email: string
  token: string
  password: string
  password_confirmation: string
}

interface UserResponse {
  success: boolean
  message: string
  data: {
    user: User
  }
}

export interface AuthResponse {
  success: boolean
  message: string
  data: {
    user: User
    token: string
    token_type: 'Bearer'
  }
}

export const authService = {
  async login(payload: AuthPayload) {
    const { data } = await api.post<AuthResponse>('/auth/login', {
      device_name: 'web',
      ...payload,
    })

    return data.data
  },

  async register(payload: RegisterPayload) {
    const { data } = await api.post<AuthResponse>('/auth/register', {
      device_name: 'web',
      ...payload,
    })

    return data.data
  },

  async forgotPassword(payload: ForgotPasswordPayload) {
    const { data } = await api.post<{ message: string }>('/auth/forgot-password', payload)

    return data.message
  },

  async resetPassword(payload: ResetPasswordPayload) {
    const { data } = await api.post<{ message: string }>('/auth/reset-password', payload)

    return data.message
  },

  async resendEmailVerification() {
    const { data } = await api.post<{ message: string }>('/auth/email/verification-notification')

    return data.message
  },

  async verifyEmail(verificationUrl: string) {
    const { data } = await api.get<UserResponse>(verificationUrl)

    return data
  },

  async me() {
    const { data } = await api.get<{ data: { user: User } }>('/auth/me')

    return data.data.user
  },

  async logout() {
    await api.post('/auth/logout')
  },
}
