<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    private const MOCK_OTP_CODE = '123456';

    public function register(RegisterRequest $request)
    {
        $fields = $request->validated();

        $user = User::create([
            'role' => $fields['role'],
            'nome' => $fields['nome'],
            'telefone' => $fields['telefone'],
            'email' => $fields['email'],
            'endereco' => $fields['endereco'],
            'foto_uri' => $fields['fotoUri'] ?? null,
            'password' => $fields['password'],
            'bi' => $fields['bi'] ?? null,
            'carta_conducao' => $fields['cartaConducao'] ?? null,
            'tipo_veiculo' => $fields['tipoVeiculo'] ?? null,
            'seguro' => $fields['seguro'] ?? null,
            'nome_loja' => $fields['nomeLoja'] ?? null,
            'categoria' => $fields['categoria'] ?? null,
            'nuit' => $fields['nuit'] ?? null,
        ]);

        return new UserResource($user);
    }

    public function login(Request $request)
    {
        $request->validate([
            'telefone' => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

        $user = User::where('telefone', $request->telefone)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            abort(401, 'Credenciais inválidas.');
        }

        if (is_null($user->email_verified_at)) {
            abort(403, 'Conta ainda não verificada.');
        }

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

        return [
            'user' => new UserResource($user),
            'token' => $token,
        ];
    }

    public function requestOtp(Request $request)
    {
        $request->validate(['email' => ['required', 'email']]);

        $user = User::where('email', $request->email)->first();

        if (! $user) {
            abort(404, 'Utilizador não encontrado.');
        }

        return response()->json(['message' => 'Código enviado.']);
    }

    public function verifyOtp(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
            'code' => ['required', 'string'],
        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || $request->code !== self::MOCK_OTP_CODE) {
            abort(422, 'Código inválido.');
        }

        $user->email_verified_at = now();
        $user->save();

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

        return [
            'user' => new UserResource($user),
            'token' => $token,
        ];
    }

    public function forgotPassword(Request $request)
    {
        $request->validate(['email' => ['required', 'email']]);

        $user = User::where('email', $request->email)->first();

        if (! $user) {
            abort(404, 'Utilizador não encontrado.');
        }

        return response()->json(['message' => 'Código enviado.']);
    }

    public function resetPassword(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
            'code' => ['required', 'string'],
            'password' => ['required', 'string', 'min:6'],
        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || $request->code !== self::MOCK_OTP_CODE) {
            abort(422, 'Código inválido.');
        }

        $user->password = $request->password;
        $user->save();

        return response()->json(['message' => 'Senha alterada.']);
    }

    public function changePassword(Request $request)
    {
        $request->validate([
            'currentPassword' => ['required', 'string'],
            'newPassword' => ['required', 'string', 'min:6'],
        ]);

        $user = $request->user();

        if (! Hash::check($request->currentPassword, $user->password)) {
            abort(422, 'Senha actual incorrecta.');
        }

        $user->password = $request->newPassword;
        $user->save();

        return response()->json(['message' => 'Senha alterada.']);
    }

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

        return response()->json(['message' => 'Sessão terminada.']);
    }
}
