<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\PublicProfile\UsernameService;

class UsernameController extends BaseController
{
    private UsernameService $usernames;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->usernames = new UsernameService();
    }

    public function checkAvailability()
    {
        $username = strtolower(trim((string) $this->request->getGet('username')));
        if (! $username) {
            return $this->jsonValidationError(['username' => 'username query parameter is required.']);
        }

        $valid = $this->usernames->isValidFormat($username);
        $available = $valid && $this->usernames->isAvailable($username, $this->currentUser()->id ?? null);

        return $this->jsonSuccess([
            'valid'     => $valid,
            'available' => $available,
        ]);
    }

    public function suggest()
    {
        $user = $this->currentUser();
        return $this->jsonSuccess(['suggestion' => $this->usernames->suggestFromName($user->name)]);
    }

    public function status()
    {
        $user = $this->currentUser();
        return $this->jsonSuccess([
            'current_username' => $user->username,
            'change_limit'      => $this->usernames->remainingChanges($user->id),
        ]);
    }

    public function update()
    {
        $user = $this->currentUser();
        $input = $this->request->getJSON(true);
        $username = $input['username'] ?? '';

        if (! $username) {
            return $this->jsonValidationError(['username' => 'username is required.']);
        }

        try {
            if ($user->username === null) {
                $this->usernames->setInitial($user->id, $username);
            } else {
                $this->usernames->change($user->id, $username);
            }
        } catch (\InvalidArgumentException $e) {
            return $this->jsonError([['code' => 'INVALID_USERNAME', 'message' => $e->getMessage()]], 422);
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'CHANGE_LIMIT_EXCEEDED', 'message' => $e->getMessage()]], 429);
        }

        return $this->jsonSuccess(['username' => strtolower(trim($username))]);
    }
}
