<?php
// src/Auth/AuthService.php
namespace App\Auth;

use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class AuthService
{
    private $userModel;
    private $jwtSecret;

    public function __construct()
    {
        $this->userModel = new User();
        $this->jwtSecret = $_ENV['JWT_SECRET'] ?? 'default_secret_for_dev';
    }

    public function createJWT(array $payload): string
    {
        $payload['iat'] = time();
        $payload['exp'] = time() + ($_ENV['SESSION_LIFETIME'] ?? 3600);
        
        return JWT::encode($payload, $this->jwtSecret, 'HS256');
    }

    public function verifyJWT(string $token): ?array
    {
        try {
            $decoded = JWT::decode($token, new Key($this->jwtSecret, 'HS256'));
            return (array) $decoded;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function createUserFromProvider(array $providerUser, string $provider, string $tenantId): string
    {
        // Check if user already exists with this provider ID
        $existingUser = $this->userModel->findByEmail($providerUser['email']);
        
        if ($existingUser) {
            // Update existing user with provider info if needed
            // For now, we'll just return the existing user ID
            return $existingUser['id'];
        }
        
        // Create a new user
        $userData = [
            'tenant_id' => $tenantId,
            'email' => $providerUser['email'],
            'password' => bin2hex(random_bytes(16)), // Placeholder password for OAuth users
            'first_name' => $providerUser['first_name'] ?? '',
            'last_name' => $providerUser['last_name'] ?? '',
            'role' => 'job_seeker', // Default role for new users
            'provider' => $provider,
            'provider_id' => $providerUser['id']
        ];
        
        return $this->userModel->create($userData);
    }

    public function getUserByProviderId(string $providerId, string $provider): ?array
    {
        return $this->userModel->findByProviderId($providerId, $provider);
    }
}