<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Collection;
use App\Models\CollectionMember;
use App\Services\CollectionCollaborationService;
use App\Services\CollectionModerationService;
use App\Services\CollectionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class CollectionModerationController extends Controller
{
    public function __construct(
        private readonly CollectionModerationService $moderation,
        private readonly CollectionService $collections,
        private readonly CollectionCollaborationService $collaborators,
    ) {
    }

    public function updateModeration(Request $request, Collection $collection): JsonResponse
    {
        $data = $request->validate([
            'moderation_status' => ['required', 'in:active,under_review,restricted,hidden'],
        ]);

        $collection = $this->moderation->updateStatus($collection->loadMissing('user'), (string) $data['moderation_status']);

        return response()->json([
            'ok' => true,
            'collection' => $this->collections->mapCollectionDetailPayload($collection->loadMissing('user'), true),
        ]);
    }

    public function updateInteractions(Request $request, Collection $collection): JsonResponse
    {
        $data = $request->validate([
            'allow_comments' => ['sometimes', 'boolean'],
            'allow_submissions' => ['sometimes', 'boolean'],
            'allow_saves' => ['sometimes', 'boolean'],
        ]);

        $collection = $this->moderation->updateInteractions($collection->loadMissing('user'), $data);

        return response()->json([
            'ok' => true,
            'collection' => $this->collections->mapCollectionDetailPayload($collection->loadMissing('user'), true),
        ]);
    }

    public function unfeature(Request $request, Collection $collection): JsonResponse
    {
        $collection = $this->moderation->unfeature($collection->loadMissing('user'));

        return response()->json([
            'ok' => true,
            'collection' => $this->collections->mapCollectionDetailPayload($collection->loadMissing('user'), true),
        ]);
    }

    public function destroyMember(Request $request, Collection $collection, CollectionMember $member): JsonResponse
    {
        $this->moderation->removeMember($collection, $member);

        return response()->json([
            'ok' => true,
            'collection' => $this->collections->mapCollectionDetailPayload($collection->fresh()->loadMissing('user'), true),
            'members' => $this->collaborators->mapMembers($collection->fresh(), $request->user()),
        ]);
    }
}
