<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
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
{
    public function login(Request $request): JsonResponse
    {
        $request->validate([
            'credential' => 'required|string',
            'password' => 'required|string',
        ]);

        $credential = trim($request->credential);

        // Determine if credential is DNI (8 digits) or email
        $user = preg_match('/^\d{8}$/', $credential)
            ? User::where('email', $credential . '@personero.local')->first()
            : User::where('email', $credential)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'credential' => ['Las credenciales proporcionadas son incorrectas.'],
            ]);
        }

        // Revoke previous tokens
        $user->tokens()->delete();

        $token = $user->createToken('auth-token')->plainTextToken;

        $userData = $this->buildUserData($user);

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

    public function me(Request $request): JsonResponse
    {
        $userData = $this->buildUserData($request->user());

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

    public function changePassword(Request $request): JsonResponse
    {
        $request->validate([
            'current_password' => 'required|string',
            'password' => 'required|string|min:6|confirmed',
        ]);

        $user = $request->user();

        if (! Hash::check($request->current_password, $user->password)) {
            throw ValidationException::withMessages([
                'current_password' => ['La contraseña actual es incorrecta.'],
            ]);
        }

        $user->update([
            'password' => Hash::make($request->password),
            'must_change_password' => false,
            'temp_password' => null,
        ]);

        return response()->json(['message' => 'Contraseña actualizada correctamente.']);
    }

    public function logout(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => 'Sesión cerrada correctamente.']);
    }

    private function buildUserData(User $user): array
    {
        $userData = [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'role' => $user->role ?? 'admin',
            'permissions' => $user->permissions ?? [],
            'must_change_password' => (bool) $user->must_change_password,
        ];

        if ($user->role === 'personero') {
            $personero = $user->personero()->with([
                'politicalParty',
                'department',
                'province',
                'district',
                'votingLocation',
                'votingTable',
            ])->first();
            $userData['personero'] = $personero;
        }

        return $userData;
    }
}
