<?php

namespace App\Console\Commands;

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

class AccountsRefreshTokensCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'accounts:refresh-tokens';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Refresh access tokens for social media accounts';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        try {
            $this->info('Refreshing account tokens...');
            
            // Get accounts that need token refresh (tokens expiring within 24 hours)
            $accounts = DB::table('social_accounts')
                ->where('status', '1') // StatusEnum::true = '1'
                ->where(function($query) {
                    $query->whereNull('access_token_expire_at')
                          ->orWhere('access_token_expire_at', '<=', now()->addHours(24));
                })
                ->get();

            $refreshedCount = 0;
            
            foreach ($accounts as $account) {
                if ($this->refreshAccountToken($account)) {
                    $refreshedCount++;
                    $this->info("Refreshed token for account: {$account->name} (ID: {$account->id})");
                }
            }

            // Update last refresh timestamp
            DB::table('settings')
                ->updateOrInsert(
                    ['key' => 'last_token_refresh'],
                    ['value' => now()->toISOString(), 'updated_at' => now()]
                );

            $message = "Token refresh completed for {$refreshedCount} accounts";
            $this->info($message);
            Log::info($message);

            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            $error = 'Error refreshing tokens: ' . $e->getMessage();
            $this->error($error);
            Log::error($error);
            return Command::FAILURE;
        }
    }

    /**
     * Refresh token for a specific account
     */
    private function refreshAccountToken($account)
    {
        try {
            // Mock token refresh (replace with actual API calls based on platform)
            $newToken = 'refreshed_token_' . time() . '_' . $account->id;
            $expiresAt = now()->addDays(60); // Most tokens expire in 60 days
            
            // Update account with new token
            DB::table('social_accounts')
                ->where('id', $account->id)
                ->update([
                    'token' => $newToken,
                    'access_token_expire_at' => $expiresAt,
                    'updated_at' => now()
                ]);

            Log::info("Token refreshed for account {$account->id}");
            return true;
            
        } catch (\Exception $e) {
            Log::error("Failed to refresh token for account {$account->id}: " . $e->getMessage());
            
            // Mark account as needs attention
            DB::table('social_accounts')
                ->where('id', $account->id)
                ->update([
                    'status' => '0', // StatusEnum::false = '0'
                    'updated_at' => now()
                ]);
                
            return false;
        }
    }
}