<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Hotel;
use App\Models\JournalEntry;
use App\Services\PackageModuleService;
use Illuminate\Support\Facades\DB;

class CleanupLeakedData extends Command
{
    protected $signature = 'hotel:cleanup-leaked-data {hotel_id?} {--dry-run}';
    protected $description = 'Remove or archive accounting entries from modules not permitted in current packages';

    public function handle(PackageModuleService $packageService)
    {
        $this->info('Starting leaked data cleanup...');
        
        $query = Hotel::query();
        if ($this->argument('hotel_id')) {
            $query->where('id', $this->argument('hotel_id'));
        }

        $hotels = $query->get();
        $totalRemoved = 0;
        $isDryRun = $this->option('dry-run');

        DB::beginTransaction();
        try {
            foreach ($hotels as $hotel) {
                $packageLevel = $hotel->package_name ?? 'silver';
                $allowedSources = $packageService->getAllowedSourcesForPackage($packageLevel);
                
                $leakedQuery = JournalEntry::where('hotel_id', $hotel->id)
                                ->whereNotIn('module_source', $allowedSources);
                
                $leakedCount = (clone $leakedQuery)->count();
                
                if ($leakedCount > 0) {
                    $this->warn("Hotel '{$hotel->name}' (Package: {$packageLevel}) has {$leakedCount} leaked entries.");
                    
                    if (!$isDryRun) {
                        $leakedQuery->delete();
                        $this->info("Deleted $leakedCount leaked entries for Hotel {$hotel->id}.");
                    }
                    $totalRemoved += $leakedCount;
                }
            }

            if ($isDryRun) {
                $this->info("DRY RUN: Found {$totalRemoved} leaked entries to clean.");
                DB::rollBack();
            } else {
                DB::commit();
                $this->info("Successfully cleaned up {$totalRemoved} leaked entries.");
            }
        } catch (\Exception $e) {
            DB::rollBack();
            $this->error("Cleanup failed: " . $e->getMessage());
            return 1;
        }

        return 0;
    }
}
