<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\ExportJob;
use App\Models\ImportJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

/**
 * Daily cleanup per docs/01-architecture.md §File storage: export/import
 * files older than 14 days are deleted from disk. The job/import records
 * themselves are kept (counts, status, audit trail) — only the file blobs
 * and their path columns are cleared, so the UI can show "expired" instead
 * of a broken download link.
 */
class PruneExpiredFiles extends Command
{
    protected $signature = 'files:prune-expired';

    protected $description = 'Delete export/import files older than 14 days (files only — job records are kept).';

    public function handle(): int
    {
        $exportsRemoved = $this->pruneExports();
        $importsRemoved = $this->pruneImports();

        $this->info("Pruned {$exportsRemoved} export file(s), {$importsRemoved} import file set(s).");

        return self::SUCCESS;
    }

    private function pruneExports(): int
    {
        $expired = ExportJob::query()
            ->whereNotNull('file_path')
            ->where('expires_at', '<', now())
            ->get();

        foreach ($expired as $job) {
            Storage::disk('local')->delete($job->file_path);
            $job->update(['file_path' => null]);
        }

        return $expired->count();
    }

    private function pruneImports(): int
    {
        $expired = ImportJob::query()
            ->where(fn ($q) => $q->where('source_path', '!=', '')->orWhereNotNull('error_report_path'))
            ->where('created_at', '<', now()->subDays(14))
            ->get();

        foreach ($expired as $job) {
            if ($job->source_path !== '') {
                Storage::disk('local')->delete($job->source_path);
            }
            if ($job->error_report_path) {
                Storage::disk('local')->delete($job->error_report_path);
            }
            $job->update(['source_path' => '', 'error_report_path' => null]);
        }

        return $expired->count();
    }
}
