<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\UserService;

class UserController extends BaseController
{
    private UserService $userService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->userService = new UserService();
    }

    public function index(): void
    {
        $filters = [
            'search' => $this->request->query('search'),
            'role' => $this->request->query('role'),
            'status' => $this->request->query('status'),
        ];

        $page = (int) ($this->request->query('page', 1));
        $perPage = (int) ($this->request->query('per_page', 15));

        $result = $this->userService->getUsers($filters, $page, $perPage);

        Response::paginated(
            $result['items'],
            $result['total'],
            $result['page'],
            $result['per_page'],
            'Usuarios consultados correctamente'
        );
    }

    public function show(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $user = $this->userService->getUser($id);
            Response::success($user, 'Usuario consultado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function store(): void
    {
        $data = $this->request->body();

        $validation = $this->validate($data, function ($v) {
            $v->required('name', 'Nombre');
            $v->required('email', 'Correo electrónico')
              ->email('email', 'Correo electrónico');
            $v->required('role', 'Rol')
              ->inValues('role', ['super_admin', 'comercial_manager'], 'Rol');
        });

        if ($validation->fails()) {
            Response::error($validation->firstError(), 422);
        }

        try {
            $user = $this->userService->createUser($data, $this->getAuthUserId());
            Response::created($user, 'Usuario creado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function update(): void
    {
        $id = (int) $this->getRouteParam('id');
        $data = $this->request->body();

        $validation = $this->validate($data, function ($v) {
            if (isset($data['email'])) {
                $v->email('email', 'Correo electrónico');
            }
            if (isset($data['role'])) {
                $v->inValues('role', ['super_admin', 'comercial_manager'], 'Rol');
            }
        });

        if ($validation->fails()) {
            Response::error($validation->firstError(), 422);
        }

        try {
            $user = $this->userService->updateUser($id, $data);
            Response::success($user, 'Usuario actualizado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function updateProfile(): void
    {
        $userId = $this->getAuthUserId();
        $data = $this->request->body();

        try {
            $user = $this->userService->updateUser($userId, $data);
            Response::success($user, 'Perfil actualizado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function toggleStatus(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $user = $this->userService->toggleStatus($id);
            $statusLabel = $user['status'] === 'active' ? 'activado' : 'desactivado';
            Response::success($user, "Usuario {$statusLabel} correctamente");
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function destroy(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $this->userService->deleteUser($id);
            Response::success(null, 'Usuario eliminado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function resendInvitation(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $user = $this->userService->resendInvitation($id, $this->getAuthUserId());
            Response::success(null, 'Invitación reenviada correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }
}
