<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use App\TierHelper;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\Media as MediaModel;

class ClearUnusedMediaFiles extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clear:unused-media';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove old unused media files from system';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $setting_override = Settings::get('app-old-media-use-expiry-days');
        $when = !empty($setting_override)
            ? Carbon::now()->subDays($setting_override)
            : Carbon::now()->subMonths(TierHelper::orphanedMediaAge(tenant('tier')));

        $query = MediaModel::query()
            ->where('created_at', '<=', $when)
            ->where(fn ($query) => $query->whereNull('last_used')->orWhere('last_used', '<=', $when))
            ->whereDoesntHave('uses');

        $this->info('Records to remove: ' . $query->count());
        $progressBar = $this->output->createProgressBar($query->count());

        $query->chunk(200, function (Collection $chunk) use ($progressBar) {
            Media::destroyMedia($chunk->pluck('id')->toArray());
            $progressBar->advance(200);
        });

        // Remove images of over 6 months that have not been added by a user and don't have uses
        // these are primarily vehicle/offer images before source_filename was correctly set to be filled
        $query = MediaModel::query()
            ->where('created_at', '<=', Carbon::now()->subMonths(6))
            ->whereNull('uploaded_by')
            ->whereNull('source_filename')
            ->whereDoesntHave('uses');

        $this->info('Records to remove: ' . $query->count());
        $progressBar = $this->output->createProgressBar($query->count());

        $query->chunk(200, function (Collection $chunk) use ($progressBar) {
            Media::destroyMedia($chunk->pluck('id')->toArray());
            $progressBar->advance(200);
        });
    }
}
