import { apiClient } from '@/services/api/client';

export interface AuthUser {
  id: number;
  full_name: string;
  email: string;
  phone_number: string;
  account_status: string;
  email_verified: boolean;
  email_verified_at: string | null;
  created_at?: string;
}
export type AuthStatus = 'success' | 'error';

export interface AuthResponse {
  status: AuthStatus;
  message: string;
  token?: string;
  user?: AuthUser;
}

export interface BasicAuthResponse {
  status: AuthStatus;
  message?: string;
}

export const authService = {
  async register(data: {
    full_name: string;
    email: string;
    phone_number: string;
    password: string;
    password_confirmation: string;
  }): Promise<AuthResponse> {
    const res = await apiClient.post('/auth/register', data);

    if (res.ok && res.data.token) {
      await apiClient.setToken(res.data.token);
    }

    return res.data;
  },

  async login(
    email: string,
    password: string
  ): Promise<AuthResponse> {
    const res = await apiClient.post('/auth/login', {
      email,
      password,
    });

    if (res.ok && res.data.token) {
      await apiClient.setToken(res.data.token);
    }

    return res.data;
  },

  async me(): Promise<{
    status: AuthStatus;
    user?: AuthUser;
  }> {
    const res = await apiClient.get('/auth/me');
    return res.data;
  },

  async logout(): Promise<void> {
    try {
      await apiClient.post('/auth/logout');
    } catch {
      // The server request may fail; still clear the local token.
    } finally {
      await apiClient.clearToken();
    }
  },

  async resendVerification(): Promise<BasicAuthResponse> {
    const res = await apiClient.post(
      '/auth/email/verification-notification'
    );

    return res.data;
  },
};

export default authService;
