<?php
declare(strict_types=1);

class SupabaseAuth {
    private static function request(string $method, string $endpoint, array $data = [], bool $useServiceKey = false): array {
        $url = rtrim(SUPABASE_URL, '/') . $endpoint;
        $key = $useServiceKey ? SUPABASE_SERVICE_ROLE_KEY : SUPABASE_SERVICE_ROLE_KEY; // Always use service key for admin actions
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        
        $headers = [
            'Content-Type: application/json',
            'apikey: ' . $key,
            'Authorization: Bearer ' . $key
        ];
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $decoded = json_decode((string)$response, true);
        
        return [
            'status' => $httpCode,
            'data' => $decoded,
            'error' => $httpCode >= 400 ? ($decoded['msg'] ?? $decoded['error_description'] ?? 'Unknown error') : null
        ];
    }

    public static function createUser(string $email, string $password): array {
        // Use Admin API to create user without email verification
        return self::request('POST', '/auth/v1/admin/users', [
            'email' => $email,
            'password' => $password,
            'email_confirm' => true
        ], true);
    }

    public static function signIn(string $email, string $password): array {
        return self::request('POST', '/auth/v1/token?grant_type=password', [
            'email' => $email,
            'password' => $password
        ]);
    }

    public static function updateUserPassword(string $uid, string $password): array {
        return self::request('PUT', '/auth/v1/admin/users/' . $uid, [
            'password' => $password
        ], true);
    }
    
    public static function getUserByEmail(string $email): ?array {
        $res = self::request('GET', '/auth/v1/admin/users', [], true);
        if ($res['status'] === 200 && isset($res['data']['users'])) {
            foreach ($res['data']['users'] as $user) {
                if ($user['email'] === $email) return $user;
            }
        }
        return null;
    }
}
