<?php

namespace App\Http\Controllers\Api;

use App\Contracts\Repositories\MatchRepositoryInterface;
use App\Events\MatchStateUpdated;
use App\Http\Controllers\Controller;
use App\Http\Resources\SponsorResource;
use App\Models\Sponsor;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Validation\Rule;

class SponsorController extends Controller
{
    public function __construct(private readonly MatchRepositoryInterface $matches) {}

    public function index(): ResourceCollection
    {
        return SponsorResource::collection(Sponsor::orderBy('sort_order')->get());
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name'       => 'required|string|max:100',
            'imageUrl'   => 'nullable|url|max:500',
            'tier'       => ['required', Rule::in(['main', 'partner'])],
            'visible'    => 'boolean',
            'sortOrder'  => 'integer',
        ]);

        $sponsor = Sponsor::create([
            'name'       => $validated['name'],
            'image_url'  => $validated['imageUrl'] ?? null,
            'tier'       => $validated['tier'],
            'visible'    => $validated['visible'] ?? true,
            'sort_order' => $validated['sortOrder'] ?? 0,
        ]);

        $this->broadcastActiveMatch();

        return (new SponsorResource($sponsor))->response()->setStatusCode(201);
    }

    public function update(Request $request, Sponsor $sponsor): SponsorResource
    {
        $validated = $request->validate([
            'name'      => 'sometimes|string|max:100',
            'imageUrl'  => 'nullable|url|max:500',
            'tier'      => ['sometimes', Rule::in(['main', 'partner'])],
            'visible'   => 'boolean',
            'sortOrder' => 'integer',
        ]);

        $sponsor->update([
            'name'       => $validated['name'] ?? $sponsor->name,
            'image_url'  => array_key_exists('imageUrl', $validated) ? $validated['imageUrl'] : $sponsor->image_url,
            'tier'       => $validated['tier'] ?? $sponsor->tier,
            'visible'    => $validated['visible'] ?? $sponsor->visible,
            'sort_order' => $validated['sortOrder'] ?? $sponsor->sort_order,
        ]);

        $this->broadcastActiveMatch();

        return new SponsorResource($sponsor->fresh());
    }

    public function destroy(Sponsor $sponsor): JsonResponse
    {
        $sponsor->delete();

        $this->broadcastActiveMatch();

        return response()->json(['message' => 'Sponsor deleted.']);
    }

    public function reorder(Request $request): JsonResponse
    {
        $request->validate(['ids' => 'required|array', 'ids.*' => 'integer|exists:sponsors,id']);

        foreach ($request->ids as $order => $id) {
            Sponsor::where('id', $id)->update(['sort_order' => $order]);
        }

        $this->broadcastActiveMatch();

        return response()->json(['ok' => true]);
    }

    /**
     * Rebroadcast the active match so all overlay subscribers receive the
     * updated sponsor list immediately without a page refresh.
     */
    private function broadcastActiveMatch(): void
    {
        $match = $this->matches->findActive();

        if ($match) {
            broadcast(new MatchStateUpdated($match));
        }
    }
}
