<?php

namespace App\Http\Controllers\Partner;

use App\Http\Controllers\Controller;
use App\Services\PartnerTokenService;
use App\Models\PartnerShow;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;

class TokenController extends Controller
{
    protected PartnerTokenService $tokenService;

    public function __construct(PartnerTokenService $tokenService)
    {
        $this->tokenService = $tokenService;
    }

    /**
     * Display the token management page.
     */
    public function index(Request $request): Response
    {
        $partner = Auth::user();

        // Get all partner shows for dropdown
        $shows = PartnerShow::where('partner_id', $partner->id)
            ->select('id', 'showId', 'title', 'is_active')
            ->orderBy('title')
            ->get();

        // Get all tokens for this partner
        $tokens = $this->tokenService->getPartnerTokens($partner->id);

        return Inertia::render('Partner/Token', [
            'shows' => $shows,
            'tokens' => $tokens,
        ]);
    }

    /**
     * Get tokens data for realtime refresh (API endpoint).
     */
    public function refresh(Request $request)
    {
        $partner = Auth::user();
        $tokens = $this->tokenService->getPartnerTokens($partner->id);

        return response()->json([
            'success' => true,
            'tokens' => $tokens,
        ]);
    }

    /**
     * Get complete token data including presence information.
     */
    public function show(Request $request, string $token)
    {
        $partner = Auth::user();

        $tokenData = $this->tokenService->getTokenData($token);

        if (! $tokenData) {
            return back()->with('error', 'Token tidak ditemukan.');
        }

        // Verify token belongs to this partner
        if ($tokenData['partner_id'] != $partner->id) {
            abort(403, 'Unauthorized action.');
        }

        $completeData = $this->tokenService->getTokenCompleteData($token);

        return response()->json([
            'success' => true,
            'data' => $completeData,
        ]);
    }

    /**
     * Generate a new token.
     */
    public function store(Request $request): RedirectResponse
    {
        $partner = Auth::user();

        $validated = $request->validate([
            'showId' => ['required', 'string', 'max:50'],
        ]);

        // Verify that the show belongs to this partner
        $show = PartnerShow::where('partner_id', $partner->id)
            ->where('showId', $validated['showId'])
            ->first();

        if (! $show) {
            return back()->withErrors([
                'showId' => 'Show tidak ditemukan atau tidak memiliki akses.',
            ]);
        }

        $tokenData = $this->tokenService->generateToken(
            $partner->id,
            $validated['showId']
        );

        return redirect()->route('partner.token.index')->with([
            'success' => 'Token berhasil dibuat.',
            'new_token' => $tokenData['token'], // Pass token to show in UI
        ]);
    }

    /**
     * Delete a token.
     */
    public function destroy(Request $request, string $token): RedirectResponse
    {
        $partner = Auth::user();

        $tokenData = $this->tokenService->getTokenData($token);

        if (! $tokenData) {
            return back()->with('error', 'Token tidak ditemukan.');
        }

        // Verify token belongs to this partner
        if ($tokenData['partner_id'] != $partner->id) {
            abort(403, 'Unauthorized action.');
        }

        $this->tokenService->deleteToken($token);

        return redirect()->route('partner.token.index')->with('success', 'Token berhasil dihapus.');
    }

    /**
     * Delete all tokens for the partner.
     */
    public function destroyAll(Request $request): RedirectResponse
    {
        $partner = Auth::user();

        $count = $this->tokenService->deletePartnerTokens($partner->id);

        return redirect()->route('partner.token.index')->with('success', "{$count} token berhasil dihapus.");
    }

    /**
     * Reset token access by removing all connected fingerprints.
     */
    public function reset(Request $request, string $token): RedirectResponse
    {
        $partner = Auth::user();

        $tokenData = $this->tokenService->getTokenData($token);

        if (! $tokenData) {
            return back()->with('error', 'Token tidak ditemukan.');
        }

        // Verify token belongs to this partner
        if ($tokenData['partner_id'] != $partner->id) {
            abort(403, 'Unauthorized action.');
        }

        $success = $this->tokenService->resetTokenAccess($token);

        if (! $success) {
            return back()->with('error', 'Gagal mereset akses token.');
        }

        return back()->with('success', 'Akses token berhasil direset.');
    }
}

