<?php

namespace App\Console\Commands;

use App\Models\UpworkSyncLog;
use App\Models\UpworkToken;
use App\Models\User;
use App\Services\UpworkAdapter;
use Illuminate\Console\Command;

class UpworkSyncWeeklyCommand extends Command
{
    protected $signature   = 'upwork:sync-weekly {--user=1 : ID del usuario propietario de las ventas}';
    protected $description = 'Sincroniza contratos de Upwork y crea/actualiza ventas en Nuna';

    public function handle(): int
    {
        $userId    = (int) $this->option('user');
        $ownerUser = User::find($userId);

        if (!$ownerUser) {
            $this->error("Usuario ID {$userId} no encontrado.");
            return self::FAILURE;
        }

        $this->info("Iniciando sync Upwork para usuario: {$ownerUser->name}");

        // Obtener el token más reciente del usuario
        // TODO: si tienes múltiples usuarios con tokens Upwork,
        //       iterar sobre todos los UpworkToken activos.
        $token   = UpworkToken::where('user_id', $ownerUser->id)->latest()->first();
        $adapter = new UpworkAdapter($token);

        $created = 0;
        $updated = 0;
        $errors  = null;

        try {
            $contracts = $adapter->fetchContracts();

            $this->info("Contratos obtenidos: " . count($contracts));

            foreach ($contracts as $contract) {
                $sale = $adapter->mapContractToSale($contract, $ownerUser);

                if ($sale->wasRecentlyCreated) {
                    $created++;
                    $this->line("  ✅ Creado: {$sale->title} (ID {$sale->id})");
                } else {
                    $updated++;
                    $this->line("  🔄 Actualizado: {$sale->title} (ID {$sale->id})");
                }
            }

            $status = 'success';
        } catch (\Throwable $e) {
            $errors  = $e->getMessage();
            $status  = 'error';
            $this->error("Error durante sync: {$errors}");
        }

        UpworkSyncLog::create([
            'status'            => $status,
            'contracts_fetched' => isset($contracts) ? count($contracts) : 0,
            'sales_created'     => $created,
            'sales_updated'     => $updated,
            'error_message'     => $errors,
            'raw_summary'       => ['user_id' => $userId, 'timestamp' => now()->toIso8601String()],
            'synced_at'         => now(),
        ]);

        $this->info("Sync completado. Creadas: {$created} | Actualizadas: {$updated}");

        return self::SUCCESS;
    }
}
