<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Seller;
use App\Models\Rfq;
use App\Models\Setting;
use Illuminate\Support\Facades\Log;

class CleanupData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'data:cleanup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Permanently delete scheduled seller accounts and old RFQs.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting data cleanup...');
        Log::info('CleanupData Command: Started.');

        // 1. Delete Requested Sellers
        $sellerMonths = (int) Setting::getValue('seller_retention_period', 3);
        $sellerCutoff = now()->subMonths($sellerMonths);
        
        $this->info("Checking for sellers requesting deletion before: {$sellerCutoff->toDateTimeString()}");

        $sellers = Seller::whereNotNull('delete_requested_at')
            ->where('delete_requested_at', '<=', $sellerCutoff)
            ->get();

        foreach ($sellers as $seller) {
            try {
                $this->info("Deleting Seller: {$seller->id} - {$seller->company_name}");
                
                $user = $seller->user;
                if ($user) {
                    $user->tokens()->delete();
                    $user->delete(); // This should cascade delete seller in DB if set up, or needs manual
                    
                    // Manual delete if cascade not set
                    if ($user->seller) {
                        $user->seller->delete();
                    }
                } else {
                    $seller->delete();
                }

                Log::info("CleanupData: Deleted Seller {$seller->id}");
            } catch (\Exception $e) {
                $this->error("Failed to delete seller {$seller->id}: " . $e->getMessage());
                Log::error("CleanupData Error deleting seller {$seller->id}: " . $e->getMessage());
            }
        }

        // 2. Delete Old RFQs
        $rfqMonths = (int) Setting::getValue('rfq_retention_period', 3);
        $rfqCutoff = now()->subMonths($rfqMonths);

        $this->info("Checking for RFQs created before: {$rfqCutoff->toDateTimeString()}");

        $deletedRfqs = Rfq::where('created_at', '<=', $rfqCutoff)->delete();
        
        $this->info("Deleted {$deletedRfqs} old RFQs.");
        Log::info("CleanupData: Deleted {$deletedRfqs} old RFQs.");

        $this->info('Cleanup complete.');
    }
}
