<?php

namespace App\Http\Controllers\Api\Biller;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Biller\LoginRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * Authenticate Biller and issue Sanctum token.
     *
     * @throws ValidationException
     */
    public function login(LoginRequest $request): JsonResponse
    {
        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials do not match our records.'],
            ]);
        }

        if ($user->role !== 'biller') {
            return response()->json([
                'message' => 'Unauthorized. Only billers can access this panel.',
            ], 403);
        }

        if (! $user->active) {
            return response()->json([
                'message' => 'Your account is inactive. Please contact support.',
            ], 403);
        }

        // Generate Sanctum plain text token
        $token = $user->createToken('biller-desktop-token')->plainTextToken;

        // Load active branch relationship if available
        $user->load('activeBranch');

        return response()->json([
            'success' => true,
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone_number' => $user->phone_number,
                'role' => $user->role,
                'active_branch_id' => $user->active_branch_id,
                'active_branch' => $user->activeBranch ? [
                    'id' => $user->activeBranch->id,
                    'name' => $user->activeBranch->name,
                ] : null,
            ],
        ]);
    }

    /**
     * Revoke Biller's current access token.
     */
    public function logout(Request $request): JsonResponse
    {
        // Revoke the token that was used to authenticate the current request
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Logged out successfully.',
        ]);
    }
}
