<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\VideoUnlock;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $query = User::query()->withCount('comments');

        if ($term = trim((string) $request->query('q', ''))) {
            $query->where(function ($q) use ($term) {
                $q->where('name', 'like', "%$term%")->orWhere('email', 'like', "%$term%");
            });
        }

        $users = $query->latest()->paginate(20)->withQueryString();

        $users->getCollection()->transform(fn (User $u) => [
            'id' => $u->id,
            'name' => $u->name,
            'email' => $u->email,
            'is_admin' => (bool) $u->is_admin,
            'banned' => $u->isBanned(),
            'comments_count' => $u->comments_count,
            'subscribed' => $u->subscription()->exists(),
            'created_at' => $u->created_at,
        ]);

        return response()->json($users);
    }

    public function ban(User $user)
    {
        $user->update(['banned_at' => Carbon::now()]);
        $user->tokens()->delete(); // revoke sessions

        return response()->json(['message' => 'User banned.']);
    }

    public function unban(User $user)
    {
        $user->update(['banned_at' => null]);

        return response()->json(['message' => 'User unbanned.']);
    }

    /** Reset all unlock state for a user (per prompt: admin can reset unlocks). */
    public function resetUnlocks(Request $request, User $user)
    {
        $videoId = $request->query('video_id');

        $unlocks = VideoUnlock::where('user_id', $user->id);
        $visits = $user->id
            ? \App\Models\AdVisit::where('user_id', $user->id)
            : null;

        if ($videoId) {
            $unlocks->where('video_id', $videoId);
            $visits?->where('video_id', $videoId);
        }

        $unlocks->delete();
        $visits?->delete();

        return response()->json(['message' => 'Unlock state reset for user.']);
    }
}
