<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class DevController extends Controller
{
    /**
     * List all users (for dev portal user switcher)
     *
     * GET /api/dev/users
     */
    public function users()
    {
        $users = User::select('id', 'name', 'phone', 'role', 'created_at')
            ->withCount('circles')
            ->get();

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

    /**
     * Generate a token for any user (dev/testing only)
     *
     * POST /api/dev/login-as/{id}
     */
    public function loginAs($id)
    {
        $user = User::find($id);

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found',
            ], 404);
        }

        // Delete old dev tokens for this user
        $user->tokens()->where('name', 'dev_token')->delete();

        // Create new token
        $token = $user->createToken('dev_token')->plainTextToken;

        return response()->json([
            'success' => true,
            'message' => "Logged in as {$user->name}",
            'data' => [
                'user' => $user,
                'token' => $token,
            ],
        ]);
    }
}
