<?php

namespace App\Console\Commands;

use App\Models\DataExport;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class PurgeExpiredDataExports extends Command
{
    protected $signature = 'exports:purge';

    protected $description = 'Delete abgelaufene Datenexporte und entfernen die entsprechenden Dateien.';

    public function handle(): int
    {
        $expired = DataExport::query()
            ->whereNotNull('expires_at')
            ->where('expires_at', '<', now())
            ->get();

        if ($expired->isEmpty()) {
            $this->info(__('profile.export.purge.none'));

            return self::SUCCESS;
        }

        $count = 0;
        foreach ($expired as $export) {
            if ($export->path && Storage::disk('local')->exists($export->path)) {
                Storage::disk('local')->delete($export->path);
            }
            $export->delete();
            $count++;
        }

        $this->info(trans_choice('profile.export.purge.deleted', $count, ['count' => $count]));

        return self::SUCCESS;
    }
}
