<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\BlulincApiService;
use App\Models\PartnerInvite;
use App\Models\Partner;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PartnerInviteUpdater extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:update-partner-invites';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetches all partner invites and their associated partners from the Blulinc API for a clean sync.';

    /**
     * The Blulinc API service instance.
     *
     * @var BlulincApiService
     */
    protected $blulincService;

    /**
     * Create a new command instance.
     *
     * @param BlulincApiService $blulincService
     * @return void
     */
    public function __construct(BlulincApiService $blulincService)
    {
        parent::__construct();
        $this->blulincService = $blulincService;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting Blulinc Partner Invites update...');
        Log::info('PartnerInviteUpdater: Command started.');

        // Opcional: Truncar las tablas para una sincronización limpia desde cero.
        // Esto es útil si este comando es la única fuente de verdad para estas tablas.
        // Si tienes otras formas de agregar datos, comenta o elimina esta sección.
        $this->info('Truncating local tables for a clean sync...');
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        PartnerInvite::truncate();
        Partner::truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        try {
            DB::beginTransaction();

            // --- FASE 1: Obtener TODAS las invitaciones primero ---
            $this->info('Phase 1: Fetching all invites from API...');
            $allInvitesFromApi = collect();
            $inviteApiCurrentPage = 1;
            $inviteApiHasMorePages = true;
            while ($inviteApiHasMorePages) {
                $inviteApiResponse = $this->blulincService->getPartnerInvites($inviteApiCurrentPage, 100);
                if (!$inviteApiResponse || empty($inviteApiResponse['data'])) {
                    break;
                }
                $allInvitesFromApi = $allInvitesFromApi->merge($inviteApiResponse['data']);
                $inviteApiMeta = $inviteApiResponse['meta'] ?? [];
                $inviteApiHasMorePages = ($inviteApiMeta['current_page'] ?? 1) < ($inviteApiMeta['last_page'] ?? 1);
                $inviteApiCurrentPage++;
            }
            $this->info("Found a total of " . $allInvitesFromApi->count() . " invites.");

            // --- FASE 2: Extraer todos los IDs de partner únicos y sincronizarlos ---
            $allPartnerIds = $allInvitesFromApi->pluck('partnerId')->filter()->unique();
            $this->info("Phase 2: Found {$allPartnerIds->count()} unique partner IDs to sync.");

            foreach ($allPartnerIds as $partnerId) {
                $partnerData = $this->blulincService->getPartnerById($partnerId);
                if ($partnerData) {
                    // Usamos el 'id' de la API como nuestra clave primaria.
                    Partner::updateOrCreate(
                        ['id' => $partnerData['id']],
                        ['name' => $partnerData['name'] ?? 'Partner Desconocido']
                    );
                } else {
                    Log::warning('Could not fetch details for partner ID. It will be skipped.', ['partner_id' => $partnerId]);
                }
            }
            $this->info("Finished syncing partners.");

            // --- FASE 3: Ahora, procesar y guardar todas las invitaciones ---
            $this->info('Phase 3: Processing and saving all invites...');
            $totalInvitesProcessed = 0;
            foreach ($allInvitesFromApi as $inviteData) {
                // Validaciones básicas
                if (empty($inviteData['id']) || empty($inviteData['userId']) || empty($inviteData['partnerId'])) {
                    continue;
                }

                // Verificamos que el partner exista en nuestra BD antes de guardar la invitación.
                // Esto es una doble seguridad.
                if (!Partner::find($inviteData['partnerId'])) {
                    Log::error('Skipping invite because its partner could not be synced.', ['invite_data' => $inviteData]);
                    continue;
                }

                $status = ($inviteData['status'] === 'accepted') ? 'accepted' : 'not accepted';
                // Usamos el 'id' de la API como nuestra clave primaria.
                PartnerInvite::updateOrCreate(
                    ['id' => $inviteData['id']],
                    [
                        'user_id' => $inviteData['userId'],
                        'partner_id' => $inviteData['partnerId'],
                        'status' => $status,
                    ]
                );
                $totalInvitesProcessed++;
            }

            DB::commit();
            $this->info("Blulinc Partner Invites update completed successfully! Processed {$totalInvitesProcessed} invites.");
            Log::info('Blulinc Partner Invites update completed successfully!', ['processed_invites' => $totalInvitesProcessed]);

        } catch (\Exception $e) {
            DB::rollBack();
            $this->error('An error occurred during Blulinc data update: ' . $e->getMessage());
            Log::error('PartnerInviteUpdater: Error during update.', ['exception' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
        }
    }
}
