<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Collection;
use App\Models\CollectionMember;
use Illuminate\Validation\ValidationException;

class CollectionModerationService
{
    public function __construct(
        private readonly CollectionService $collections,
        private readonly CollectionCollaborationService $collaborators,
    ) {
    }

    public function updateStatus(Collection $collection, string $status): Collection
    {
        if (! in_array($status, [
            Collection::MODERATION_ACTIVE,
            Collection::MODERATION_UNDER_REVIEW,
            Collection::MODERATION_RESTRICTED,
            Collection::MODERATION_HIDDEN,
        ], true)) {
            throw ValidationException::withMessages([
                'moderation_status' => 'Choose a valid moderation status.',
            ]);
        }

        return $this->collections->syncCollectionPublicState($collection, [
            'moderation_status' => $status,
        ]);
    }

    public function updateInteractions(Collection $collection, array $attributes): Collection
    {
        return $this->collections->syncCollectionPublicState($collection, $attributes);
    }

    public function unfeature(Collection $collection): Collection
    {
        return $this->collections->unfeatureCollection($collection);
    }

    public function removeMember(Collection $collection, CollectionMember $member): void
    {
        if ((int) $member->collection_id !== (int) $collection->id) {
            throw ValidationException::withMessages([
                'member' => 'This member does not belong to the selected collection.',
            ]);
        }

        if ($member->role === Collection::MEMBER_ROLE_OWNER) {
            throw ValidationException::withMessages([
                'member' => 'The collection owner cannot be removed by moderation actions.',
            ]);
        }

        $member->forceFill([
            'status' => Collection::MEMBER_STATUS_REVOKED,
            'revoked_at' => now(),
        ])->save();

        $this->collaborators->syncCollaboratorsCount($collection);
    }
}
