<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\Collection;
use App\Services\CollectionCollaborationService;
use App\Services\CollectionLifecycleService;
use App\Services\CollectionSurfaceService;
use Illuminate\Console\Command;

class SyncCollectionLifecycleCommand extends Command
{
    protected $signature = 'collections:sync-lifecycle';

    protected $description = 'Expire pending collection invites, sync collection lifecycle states, and deactivate expired placements.';

    public function handle(CollectionCollaborationService $collaborators, CollectionLifecycleService $lifecycle, CollectionSurfaceService $surfaces): int
    {
        $expiredInvites = $collaborators->expirePendingInvites();
        $lifecycleResults = $lifecycle->syncScheduledCollections();
        $expiredPlacements = $surfaces->syncPlacements();

        $unfeaturedCollections = Collection::query()
            ->where('is_featured', true)
            ->whereNotNull('unpublished_at')
            ->where('unpublished_at', '<=', now())
            ->update([
                'is_featured' => false,
                'featured_at' => null,
                'updated_at' => now(),
            ]);

        $this->info(sprintf(
            'Expired %d pending invites; published %d scheduled collections; expired %d collections; unfeatured %d unpublished collections; deactivated %d expired placements.',
            $expiredInvites,
            (int) ($lifecycleResults['scheduled'] ?? 0),
            (int) ($lifecycleResults['expired'] ?? 0),
            $unfeaturedCollections,
            $expiredPlacements,
        ));

        return self::SUCCESS;
    }
}
