<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
class MultiTenantAuthService
{
    /**
     * Authenticate user against both master and tenant databases
     */
    public static function authenticate($email, $password)
    {
        try {
            $masterUser = DB::connection('mysql')->table('users')
                ->where('email', $email)
                ->first();

            if (!$masterUser) {
                Log::info('User not found in master database', ['email' => $email]);
                return false;
            }

            if (!Hash::check($password, $masterUser->password)) {
                Log::info('Password mismatch in master database', ['email' => $email]);
                return false;
            }

            config(['database.connections.temp_tenant' => [
                'driver' => 'mysql',
                'host' => '127.0.0.1',
                'port' => '3306',
                'database' => $masterUser->tenant_database,
                'username' => $masterUser->tenant_username,
                'password' => $masterUser->tenant_password,
            ]]);

            $tenantUser = DB::connection('temp_tenant')->table('users')
                ->where('email', $email)
                ->first();

            if (!$tenantUser) {
                Log::info('User not found in tenant database', [
                    'email' => $email,
                    'tenant_db' => $masterUser->tenant_database
                ]);
                return false;
            }

            if (!Hash::check($password, $tenantUser->password)) {
                Log::info('Password mismatch in tenant database', [
                    'email' => $email,
                    'tenant_db' => $masterUser->tenant_database
                ]);
                return false;
            }

            Log::info('Authentication successful for both databases', [
                'email' => $email,
                'tenant_db' => $masterUser->tenant_database
            ]);

            return $masterUser;

        } catch (\Exception $e) {
            Log::error('Authentication error', [
                'email' => $email,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
}
