/**
 * OAuth API
 * Handles OAuth authentication flows with various providers
 */

import apiClient from './client';

export interface OAuthProvider {
  name: string;
  display_name: string;
  icon: string;
}

export interface OAuthAuthorizationResponse {
  authorization_url: string;
}

export interface OAuthTokenResponse {
  access: string;
  refresh: string;
  user: {
    id: number;
    username: string;
    email: string;
    name: string;
    role: string;
    avatar_url?: string;
    is_staff: boolean;
    is_superuser: boolean;
    business?: number;
    business_name?: string;
    business_subdomain?: string;
  };
}

export interface OAuthConnection {
  id: string;
  provider: string;
  provider_user_id: string;
  email?: string;
  connected_at: string;
}

/**
 * Get list of enabled OAuth providers
 */
export const getOAuthProviders = async (): Promise<OAuthProvider[]> => {
  const response = await apiClient.get<{ providers: OAuthProvider[] }>('/api/auth/oauth/providers/');
  return response.data.providers;
};

/**
 * Initiate OAuth flow - get authorization URL
 */
export const initiateOAuth = async (provider: string): Promise<OAuthAuthorizationResponse> => {
  const response = await apiClient.get<OAuthAuthorizationResponse>(
    `/api/auth/oauth/${provider}/authorize/`
  );
  return response.data;
};

/**
 * Handle OAuth callback - exchange code for tokens
 */
export const handleOAuthCallback = async (
  provider: string,
  code: string,
  state: string
): Promise<OAuthTokenResponse> => {
  const response = await apiClient.post<OAuthTokenResponse>(
    `/api/auth/oauth/${provider}/callback/`,
    {
      code,
      state,
    }
  );
  return response.data;
};

/**
 * Get user's connected OAuth accounts
 */
export const getOAuthConnections = async (): Promise<OAuthConnection[]> => {
  const response = await apiClient.get<{ connections: OAuthConnection[] }>('/api/auth/oauth/connections/');
  return response.data.connections;
};

/**
 * Disconnect an OAuth account
 */
export const disconnectOAuth = async (provider: string): Promise<void> => {
  await apiClient.delete(`/api/auth/oauth/connections/${provider}/`);
};
