<?php

namespace App\Http\Controllers;

use App\Actions\Records\CreatePlayerRecordAction;
use App\Http\Requests\Records\StorePlayerRecordRequest;
use App\Models\PlayerRecord;
use App\Queries\GameCatalogQuery;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use InvalidArgumentException;

class PlayerRecordController extends Controller
{
    public function __construct(private GameCatalogQuery $gameCatalog) {}

    public function index(): View
    {
        $this->authorize('viewAny', PlayerRecord::class);

        $profile = auth()->user()->playerProfile;

        $records = $profile
            ? $profile->records()
                ->with(['game', 'rank', 'media'])
                ->latest()
                ->paginate(12)
            : PlayerRecord::query()->whereRaw('1 = 0')->paginate(12);

        return view('pages.profile.records.index', [
            'records' => $records,
            'games' => $this->gameCatalog->allActive(),
            'gameProfiles' => $profile?->gameProfiles()->with('game')->get() ?? collect(),
        ]);
    }

    public function store(
        StorePlayerRecordRequest $request,
        CreatePlayerRecordAction $action,
    ): RedirectResponse {
        try {
            $action->execute(
                auth()->user(),
                $request->validated(),
                $request->file('screenshots', []),
            );
        } catch (InvalidArgumentException $exception) {
            return back()->withInput()->withErrors(['record' => $exception->getMessage()]);
        }

        return redirect()
            ->route('profile.records.index')
            ->with('status', __('admin.moderation.records').' saved.');
    }

    public function destroy(PlayerRecord $record): RedirectResponse
    {
        $this->authorize('delete', $record);
        $record->delete();

        return redirect()
            ->route('profile.records.index')
            ->with('status', 'Record deleted.');
    }
}
