<?php

namespace App\Console\Commands;

use App\Models\Commons\File;
use App\Models\Tenants\Tenant;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Permanently delete trashed files older than 30 days';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $threshold = now()->subDays(30);

        $files = File::onlyTrashed()
            ->where('deleted_at', '<', $threshold)
            ->get();

        $count = $files->count();
        $this->info("Found {$count} files in trash to permanently delete");

        $deleted = 0;
        foreach ($files as $file) {
            try {
                $this->permanentDelete($file);
                $deleted++;
            } catch (\Exception $e) {
                $this->error("Failed to permanently delete file ID {$file->id}: {$e->getMessage()}");
            }
        }

        $this->info("Trash cleanup completed: {$deleted}/{$count} files deleted");

        return Command::SUCCESS;
    }

    /**
     * Permanently delete a file
     */
    private function permanentDelete(File $file): void
    {
        DB::transaction(function () use ($file) {
            // Delete physical file
            if (Storage::disk('tenant')->exists($file->file_path)) {
                Storage::disk('tenant')->delete($file->file_path);
            }

            // Update tenant storage usage
            $tenant = Tenant::find($file->tenant_id);
            if ($tenant) {
                $tenant->decrement('storage_used', $file->file_size);
            }

            // Update deletion log
            DB::table('file_deletion_logs')
                ->where('file_id', $file->id)
                ->where('deletion_type', 'soft')
                ->update(['deletion_type' => 'permanent']);

            // Force delete from DB
            $file->forceDelete();
        });
    }
}
