<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Mtc\MercuryDataModels\VehicleOffer;

class UnpublishExpiredContent extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'content:unpublish-expired';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Unpublish pages and vehicle offers where the unpublish date has passed';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $now = Carbon::now();

        $this->unpublishPages($now);
        $this->unpublishVehicleOffers($now);

        return 0;
    }

    private function unpublishPages(Carbon $now): void
    {
        $pageModel = Config::get('pages.page_model');

        if (!$pageModel || !class_exists($pageModel)) {
            $this->warn('Page model not configured');
            return;
        }

        $count = $pageModel::query()
            ->where('status', 'published')
            ->whereNotNull('unpublished_at')
            ->where('unpublished_at', '<=', $now)
            ->update(['status' => 'draft']);

        if ($count > 0) {
            $this->info("Unpublished {$count} page(s)");
        }
    }

    private function unpublishVehicleOffers(Carbon $now): void
    {
        $count = VehicleOffer::query()
            ->where('published', true)
            ->whereNotNull('unpublished_at')
            ->where('unpublished_at', '<=', $now)
            ->update(['published' => false]);

        if ($count > 0) {
            $this->info("Unpublished {$count} vehicle offer(s)");
        }
    }
}
