import type { Session, User, AuthError } from '@supabase/supabase-js';
import { supabase } from './supabase';

/**
 * Auth response types
 */
export interface AuthResult {
  success: boolean;
  error?: string;
}

export interface SignInResult extends AuthResult {
  user?: User;
  session?: Session;
}

export interface SessionResult {
  session: Session | null;
  error?: string;
}

export interface UserResult {
  user: User | null;
  error?: string;
}

/**
 * Helper function to extract error message from AuthError
 */
function getErrorMessage(error: AuthError | null): string | undefined {
  if (!error) return undefined;
  return error.message || 'An unknown error occurred';
}

/**
 * Sign in with email and password
 * @param email - User's email address
 * @param password - User's password
 * @returns SignInResult with user and session on success, or error on failure
 */
export async function signIn(email: string, password: string): Promise<SignInResult> {
  try {
    const { data, error } = await supabase.auth.signInWithPassword({
      email: email.trim().toLowerCase(),
      password,
    });

    if (error) {
      return {
        success: false,
        error: getErrorMessage(error),
      };
    }

    return {
      success: true,
      user: data.user ?? undefined,
      session: data.session ?? undefined,
    };
  } catch (error) {
    console.error('Sign in error:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to sign in',
    };
  }
}

/**
 * Sign out the current user and clear the session
 * @returns AuthResult indicating success or failure
 */
export async function signOut(): Promise<AuthResult> {
  try {
    const { error } = await supabase.auth.signOut();

    if (error) {
      return {
        success: false,
        error: getErrorMessage(error),
      };
    }

    return { success: true };
  } catch (error) {
    console.error('Sign out error:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to sign out',
    };
  }
}

/**
 * Get the current session
 * @returns SessionResult with the current session or null
 */
export async function getSession(): Promise<SessionResult> {
  try {
    const { data, error } = await supabase.auth.getSession();

    if (error) {
      return {
        session: null,
        error: getErrorMessage(error),
      };
    }

    return { session: data.session };
  } catch (error) {
    console.error('Get session error:', error);
    return {
      session: null,
      error: error instanceof Error ? error.message : 'Failed to get session',
    };
  }
}

/**
 * Get the current user
 * @returns UserResult with the current user or null
 */
export async function getCurrentUser(): Promise<UserResult> {
  try {
    const { data, error } = await supabase.auth.getUser();

    if (error) {
      return {
        user: null,
        error: getErrorMessage(error),
      };
    }

    return { user: data.user };
  } catch (error) {
    console.error('Get current user error:', error);
    return {
      user: null,
      error: error instanceof Error ? error.message : 'Failed to get current user',
    };
  }
}

/**
 * Refresh the current session
 * @returns SessionResult with the refreshed session
 */
export async function refreshSession(): Promise<SessionResult> {
  try {
    const { data, error } = await supabase.auth.refreshSession();

    if (error) {
      return {
        session: null,
        error: getErrorMessage(error),
      };
    }

    return { session: data.session };
  } catch (error) {
    console.error('Refresh session error:', error);
    return {
      session: null,
      error: error instanceof Error ? error.message : 'Failed to refresh session',
    };
  }
}

/**
 * Check if the user is currently authenticated
 * @returns boolean indicating if user is authenticated
 */
export async function isAuthenticated(): Promise<boolean> {
  const { session } = await getSession();
  return session !== null;
}

/**
 * Sign up with email and password (for future use)
 * @param email - User's email address
 * @param password - User's password
 * @returns SignInResult with user on success
 */
export async function signUp(email: string, password: string): Promise<SignInResult> {
  try {
    const { data, error } = await supabase.auth.signUp({
      email: email.trim().toLowerCase(),
      password,
    });

    if (error) {
      return {
        success: false,
        error: getErrorMessage(error),
      };
    }

    return {
      success: true,
      user: data.user ?? undefined,
      session: data.session ?? undefined,
    };
  } catch (error) {
    console.error('Sign up error:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to sign up',
    };
  }
}
