<?php

declare(strict_types=1);

namespace App\Uploads\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

final class CleanupService
{
    public function cleanupStaleDrafts(int $limit = 100): int
    {
        $limit = max(1, min(100, $limit));
        $now = now();
        $inactiveThreshold = $now->copy()->subDay();

        $drafts = DB::table('uploads')
            ->select(['id'])
            ->where('status', 'draft')
            ->where(function ($query) use ($now, $inactiveThreshold): void {
                $query->where('expires_at', '<', $now)
                    ->orWhere(function ($inner) use ($inactiveThreshold): void {
                        $inner->where('updated_at', '<', $inactiveThreshold)
                            ->where('status', '!=', 'published');
                    });
            })
            ->orderBy('updated_at')
            ->limit($limit)
            ->get();

        if ($drafts->isEmpty()) {
            Log::info('Upload cleanup completed', ['deleted' => 0]);
            return 0;
        }

        $deleted = 0;

        DB::transaction(function () use ($drafts, &$deleted): void {
            foreach ($drafts as $draft) {
                $uploadId = (string) $draft->id;

                DB::table('uploads')->where('id', $uploadId)->delete();
                Storage::disk('local')->deleteDirectory('tmp/drafts/' . $uploadId);

                $deleted++;
            }
        });

        Log::info('Upload cleanup completed', ['deleted' => $deleted]);

        return $deleted;
    }
}
