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

import { apiClient } from "../client";

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

export interface AuthTokens {
  access: string;
  refresh?: string;
}

export type AuthTokenValue = string | AuthTokens;

export interface LoginRequest {
  identifier: string;
  password: string;
}

export interface RegisterRequest {
  username: string;
  email: string;
  phone_number: string;
  password: string;
  first_name?: string;
  last_name?: string;
}

export interface AuthResponse {
  code: number;
  msg: string;
  data: AuthUser;
  token: AuthTokenValue;
}

export interface RefreshTokenResponse {
  access: string;
}

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

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

const storeAuthToken = (token: AuthTokenValue | null | undefined): void => {
  if (!token) return;

  if (typeof token === "string") {
    apiClient.setAuthToken(token);

    return;
  }

  if (token.access) {
    apiClient.setAuthToken(token.access);
  }

  if (token.refresh) {
    apiClient.setRefreshToken(token.refresh);
  }
};

export const authService = {
  /**
   * Login with username, email, or phone number
   */
  async login(payload: LoginRequest): Promise<AuthResponse> {
    const response = await apiClient.post<AuthResponse>(
      "/api/auth/login/",
      payload,
    );

    storeAuthToken(response.token);

    return response;
  },

  /**
   * Register a new user
   */
  async register(payload: RegisterRequest): Promise<AuthResponse> {
    const response = await apiClient.post<AuthResponse>(
      "/api/auth/register/",
      payload,
    );

    storeAuthToken(response.token);

    return response;
  },

  /**
   * Refresh access token
   */
  async refreshToken(refresh: string): Promise<RefreshTokenResponse> {
    const response = await apiClient.post<RefreshTokenResponse>(
      "/api/auth/token/refresh/",
      { refresh },
    );

    if (response.access) {
      apiClient.setAuthToken(response.access);
    }

    return response;
  },

  /**
   * Update user profile
   */
  async updateProfile(
    payload: UpdateProfilePayload,
  ): Promise<UpdateProfileResponse> {
    const response = await apiClient.patch<UpdateProfileResponse>(
      "/api/account/profile/",
      payload,
    );

    if (response.code !== 200 || !response.data) {
      throw new Error(response.msg || "Failed to update profile");
    }

    return response;
  },

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