<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Requests\LoginRequest;
use App\Models\Video;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

        $user = User::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'password' => Hash::make($request->password),
            'role_id'  => 2,
        ]);

        try {
            $token = JWTAuth::fromUser($user);
        } catch (JWTException $e) {
            return response()->json(['error' => 'Could not create token'], 500);
        }

        $user->load('role');

        return response()->json([
            'token' => $token,
            'user'  => $user,
        ], 201);
    }

    public function login(LoginRequest $request)
    {
        $login = JWTAuth::attempt([
            "email" => $request->email,
            "password" => $request->password
        ]);

        if (!$login) {
            return response()->json([
                'message' => 'Credenciais inválidas',
                'errors' => null,
            ], 400);
        }

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

        $token = JWTAuth::claims([
            "role_id" => $user->role_id
        ])->fromUser($user);

        return response()->json([
            "access_token" => $token,
            "token_type" => "Bearer",
            "expires_in" => JWTAuth::factory()->getTTL() * 60,
            "user" => [
                "id" => $user->id,
                "name" => $user->name,
                "email" => $user->email,
                "role_id" => $user->role_id,
                "created_at" => $user->created_at,
            ],
        ]);
    }

    public function refresh(Request $request)
    {
        try {
            $newAccessToken = JWTAuth::setToken($request->refresh_token)->refresh();
        } catch (JWTException $e) {
            return response()->json(['error' => 'Refresh token expirado, faça login novamente'], 401);
        }

        return response()->json([
            'access_token' => $newAccessToken,
            'expires_in'   => JWTAuth::factory()->getTTL() * 60,
        ]);
    }

    public function logout()
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
        } catch (JWTException $e) {
            return response()->json(['error' => 'Erro ao realizar logout, tente novamente'], 500);
        }

        return redirect()->route('login');
    }

    public function me()
    {
        $user = auth()->user();
        $userId = $user->id;
        $role = $user->role_id;
        $userSector = $user->sector_id;

        if ($role !== 1) {
            $stats = Video::query()
                ->where('is_active', true)
                ->whereHas('sectors', function ($s) use ($userSector) {
                    $s->where('sectors.id', $userSector)
                      ->orWhere('sectors.slug', "global");
                })
                ->selectRaw('
                    COUNT(*) as active_count,
                    COUNT(CASE WHEN EXISTS (
                        SELECT 1 FROM video_views
                        WHERE video_views.video_id = videos.id
                        AND video_views.user_id = ?
                    ) THEN 1 END) as watched_count
                ', [$userId])
                ->first();
        } else {
            $stats = Video::selectRaw('
                COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count,
                COUNT(CASE WHEN is_active = 1 AND EXISTS (
                    SELECT 1 FROM video_views
                    WHERE video_views.video_id = videos.id
                    AND video_views.user_id = ?
                ) THEN 1 END) as watched_count
            ', [$userId])
                ->first();
        }

        return response()->json([
            'message' => 'Utilizador obtido com sucesso',
            'data' => [
                'id' => $user->id,
                'role_id' => $user->role_id,
                'videosWatched' => $stats->watched_count ?? 0,
                'videosCount' => $stats->active_count ?? 0,
            ],
            'errors' => null,
        ], 200);
    }
}
