import { supabase } from '@/lib/supabase'
import type { AuthService, AuthUser } from './types'

export class SupabaseAuthService implements AuthService {
  async signInWithGoogle(): Promise<void> {
    const { error } = await supabase.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.origin },
    })
    if (error) throw error
  }

  async signOut(): Promise<void> {
    const { error } = await supabase.auth.signOut()
    if (error) throw error
  }

  async getCurrentUser(): Promise<AuthUser | null> {
    const { data: { session } } = await supabase.auth.getSession()
    if (!session?.user) return null
    return this.buildAuthUser(session.user)
  }

  onAuthStateChange(callback: (user: AuthUser | null) => void): () => void {
    const { data: { subscription } } = supabase.auth.onAuthStateChange(
      async (event, session) => {
        if (!session?.user) {
          callback(null)
          return
        }

        if (event === 'SIGNED_IN') {
          const email = session.user.email ?? ''
          const role = email.endsWith('@inquality.com.py') ? 'platform_admin' : 'guest'
          await supabase.from('users').upsert(
            {
              id: session.user.id,
              name: session.user.user_metadata?.full_name ?? email,
              avatar_url: session.user.user_metadata?.avatar_url ?? null,
              platform_role: role,
            },
            { onConflict: 'id', ignoreDuplicates: true }
          )
        }

        const user = await this.buildAuthUser(session.user)
        callback(user)
      }
    )

    return () => subscription.unsubscribe()
  }

  private async buildAuthUser(supabaseUser: { id: string; email?: string; user_metadata?: Record<string, unknown> }): Promise<AuthUser> {
    const email = supabaseUser.email ?? ''
    const { data: row } = await supabase
      .from('users')
      .select('name, avatar_url, platform_role')
      .eq('id', supabaseUser.id)
      .single()

    return {
      id: supabaseUser.id,
      email,
      name: row?.name ?? supabaseUser.user_metadata?.full_name as string ?? email,
      avatarUrl: row?.avatar_url ?? supabaseUser.user_metadata?.avatar_url as string ?? undefined,
      platformRole: (row?.platform_role ?? 'guest') as AuthUser['platformRole'],
    }
  }
}
