<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Mail\VerifyEmail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Response;
use Exception;

class AuthController extends Controller
{
    public function createUser(Request $request)
    {
        $validatedData = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|unique:users|max:255',
            'password' => 'required|string|min:8|max:12',
        ]);

        if ($validatedData->fails()) {
            return response()->json(['error' => $validatedData->errors()->toArray()], 400);
        }
        try {
            $hashedPassword = Hash::make($request->password);
            $tokenEmail = bin2hex(random_bytes(64));
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => $hashedPassword,
                'role_id' => Role::where('name', 'owner')->first()->role_id,
                'email_verification_token' => $tokenEmail,
            ]);
            $this->sendEmailVerification($user);
            return response()->json([
                'message' => "Revisa tu correo para confirmar tu cuenta.",
            ], Response::HTTP_OK);
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al crear el usuario"], 500);
        }
    }

    public function authenticate(Request $request)
    {
        $validatedData = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255|exists:users,email',
            'password' => 'required|string|max:50',
        ]);

        if ($validatedData->fails()) {
            return response()->json(['error' => $validatedData->errors()->toArray()], 400);
        }
        try {
            $credentials = $request->only('email', 'password');
            if (Auth::attempt($credentials)) {
                $user = User::where('email', $request->email)->first();
                if (is_null($user->email_verified_at)) {
                    $tokenEmail = bin2hex(random_bytes(64));
                    $user->email_verification_token = $tokenEmail;
                    $user->save();
                    $this->sendEmailVerification($user);
                    return response()->json(['error' => "Debes verificar tu correo electrónico antes de iniciar sesión. Hemos reenviado el correo de confirmación."], 500);
                }
                $token = $user->createToken('api_token')->plainTextToken;
                return response()->json([
                    'token' => $token,
                    'user' => [
                        'id' => $user->id,
                        'name' => $user->name,
                        'email' => $user->email,
                        'role' => $user->role->name,
                    ],
                    'customer_id' => $user->stripe_customer_id
                ]);
            }
            return response()->json(['message' => 'Accesos incorretos'], 401);
        } catch (Exception $ex) {
            return response()->json(['error' => "Ocurrio un error inesperado al intentar autenticar."], 500);
        }
    }

    public function logout(Request $request)
    {
        $validatedData = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255|exists:users,email',
        ]);

        if ($validatedData->fails()) {
            return response()->json(['error' => $validatedData->errors()->toArray()], 400);
        }
        try {
            $user = User::where("email", $request->email)->first();
            $user->tokens()->delete();
            return response()->json(['message' => "Vuelve pronto."], 201);
        } catch (Exception $ex) {
            return response()->json(['error' => "Error al finalizar la sesión"], 500);
        }
    }

    protected function sendEmailVerification(User $user)
    {
        $url = url('/api/email/verify/' . $user->id . '/' . $user->email_verification_token);

        Mail::to($user->email)->send(new VerifyEmail($user, $url));
    }
}
