import { apiClient } from '@/services/api/client';
import {
  AuthResponse,
  CheckUsernameRequest,
  CheckUsernameResponse,
  LoginCredentials,
  MessageResponse,
  RefreshResponse,
  RegisterCredentials,
  RequestPasswordResetRequest,
  ResendVerificationRequest,
  ResetPasswordRequest,
  User,
  VerifyEmailRequest,
} from '../types/index';

export const authApi = {
  login: async (credentials: LoginCredentials): Promise<AuthResponse> => {
    const { data } = await apiClient.post<AuthResponse>(
      '/auth/login',
      credentials,
    );
    return data;
  },

  register: async (payload: RegisterCredentials): Promise<AuthResponse> => {
    const { data } = await apiClient.post<AuthResponse>(
      '/auth/register',
      payload,
    );
    return data;
  },

  getMe: async (): Promise<User> => {
    const { data } = await apiClient.get<User>('/auth/me');
    return data;
  },

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

  logout: async (refreshToken: string): Promise<void> => {
    await apiClient.post('/auth/logout', { refresh_token: refreshToken });
  },

  verifyEmail: async (request: VerifyEmailRequest): Promise<MessageResponse> => {
    const { data } = await apiClient.post<MessageResponse>(
      '/auth/verify-email',
      undefined,
      {
        params: { token: request.token },
      },
    );
    return data;
  },

  resendVerification: async (
    request: ResendVerificationRequest,
  ): Promise<MessageResponse> => {
    const { data } = await apiClient.post<MessageResponse>(
      '/auth/resend-verification',
      request,
    );
    return data;
  },

  checkUsername: async (
    request: CheckUsernameRequest,
  ): Promise<CheckUsernameResponse> => {
    const { data } = await apiClient.get<CheckUsernameResponse>(
      '/auth/check-username',
      {
        params: { username: request.username },
      },
    );
    return data;
  },

  requestPasswordReset: async (
    request: RequestPasswordResetRequest,
  ): Promise<MessageResponse> => {
    const { data } = await apiClient.post<MessageResponse>(
      '/auth/password/reset-request',
      request,
    );
    return data;
  },

  resetPassword: async (
    request: ResetPasswordRequest,
  ): Promise<MessageResponse> => {
    const { data } = await apiClient.post<MessageResponse>(
      '/auth/password/reset',
      request,
    );
    return data;
  },
};
