<?php
declare(strict_types=1);

namespace Controllers;

use Helpers\Auth;
use Helpers\Request;
use Helpers\Response;
use Services\AuthService;
use Validators\Validator;

final class AuthController
{
    public function register(): never
    {
        $data = Request::input();
        $errors = Validator::validate($data, ['name'=>'required|min:2', 'email'=>'required|email', 'password'=>'required|min:6']);
        if ($errors) Response::error('Validation failed', 422, $errors);
        try { Response::success((new AuthService())->register($data), 'Registered successfully', 201); }
        catch (\Throwable $e) { Response::error($e->getMessage(), 400); }
    }

    public function login(): never
    {
        $data = Request::input();
        $errors = Validator::validate($data, ['email'=>'required|email', 'password'=>'required']);
        if ($errors) Response::error('Validation failed', 422, $errors);
        try { Response::success((new AuthService())->login($data), 'Logged in successfully'); }
        catch (\Throwable $e) { Response::error($e->getMessage(), 401); }
    }

    public function logout(): never
    {
        (new AuthService())->logout(Auth::token());
        Response::success([], 'Logged out');
    }

    public function me(): never
    {
        try { $u = Auth::requireUser(); Response::success(['user' => ['id'=>$u['id'], 'name'=>$u['name'], 'email'=>$u['email'], 'phone'=>$u['phone'], 'role'=>$u['role']]]); }
        catch (\Throwable $e) { Response::error('Authentication required', 401); }
    }
}
