<?php

namespace Controllers;

use Libs\ResponseLib;
use Models\UserModel;
use Psr\Http\Message\ServerRequestInterface;
use Respect\Validation\Validator as val;
use Respect\Validation\Exceptions\ValidationException;

class UserChangeEmailController
{
    private UserModel $model;

    public function __construct()
    {
        $this->model = new UserModel();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $userId = (int)($request->getAttribute('api_user_id') ?? 0);
        if ($userId <= 0) {
            return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
        }

        $body = json_decode((string)$request->getBody(), true) ?? [];

        try {
            val::key('email', val::email())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        $email = trim($body['email']);

        $ok = $this->model->updateEmail($userId, $email);
        if (!$ok) {
            return ResponseLib::sendFail('Email already in use or update failed', [], 'E_VALIDATE')->withStatus(400);
        }

        return ResponseLib::sendOk(['user_id' => $userId, 'user_email' => $email], 'S_UPDATED');
    }
}