<?php

namespace App\Console\Commands;


use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class CleanupPasswordResets extends Command
{
    protected $signature = 'password:cleanup';
    protected $description = 'Clean up expired password reset tokens';

    public function handle()
    {
        try {
            $masterConfig = [
                'driver' => 'mysql',
                'host' => env('DB_HOST', '127.0.0.1'),
                'port' => env('DB_PORT', '3306'),
                'database' => env('DB_DATABASE'),
                'username' => env('DB_USERNAME'),
                'password' => env('DB_PASSWORD'),
                'charset' => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci',
                'prefix' => '',
                'strict' => true,
                'engine' => null,
            ];

            config(['database.connections.master_cleanup' => $masterConfig]);

            // Delete tokens older than 24 hours
            $deletedCount = DB::connection('master_cleanup')
                ->table('password_resets')
                ->where('created_at', '<', Carbon::now()->subHours(24))
                ->delete();

            DB::purge('master_cleanup');

            $this->info("Cleaned up {$deletedCount} expired password reset tokens.");

        } catch (\Exception $e) {
            $this->error("Failed to cleanup password reset tokens: " . $e->getMessage());
        }
    }
}

// ENHANCED AUTHENTICATION FUNCTION
// Update your existing authentication function to handle password resets

function authenticateUser($email, $password)
{
    try {
        // Step 1: Get user from master database (current default connection)
        $masterUser = DB::table('users')->where('email', $email)->first();

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

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

        // Step 3: Set up tenant connection
        $tenantConfig = [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => $masterUser->tenant_database,
            'username' => $masterUser->tenant_username,
            'password' => $masterUser->tenant_password,
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ];

        // Add tenant connection to config
        config(['database.connections.tenant_check' => $tenantConfig]);

        // Step 4: Check user in tenant database
        $tenantUser = DB::connection('tenant_check')->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;
        }

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

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

        return $masterUser;

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