<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Common\CrmUserManager;
use PloverCRM\Common\StandalonePasswordManager;
use PloverCRM\Core\Api\AbstractEndpoint;
use WP_REST_Request;

/**
 * Current-user standalone password management.
 *
 * GET  /wp-json/plover-crm/v1/access-password
 * POST /wp-json/plover-crm/v1/access-password
 */
class AccessPasswordEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/access-password';
    }

    public function getMethod()
    {
        return ['GET', 'POST'];
    }

    public function handle(WP_REST_Request $request)
    {
        $method = $request->get_method();

        if ($method === 'GET') {
            return $this->getPassword();
        }

        if ($method === 'POST') {
            return $this->regeneratePassword();
        }

        return $this->error('The requested endpoint or method is not valid', 400, 'invalid_request');
    }

    private function getPassword()
    {
        $profile = CrmUserManager::getCurrentProfile();

        if (!$profile) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        $bundle = StandalonePasswordManager::getPasswordBundle((int) $profile['id'], [
            'rotated_by_user_id' => get_current_user_id() ?: null,
        ]);

        if (!$bundle) {
            return $this->error('Unable to load the sign-in details for this account', 500, 'password_unavailable');
        }

        return $this->success([
            'password' => $bundle['password'],
            'record' => $bundle['record'],
            'share' => $bundle['share'],
        ]);
    }

    private function regeneratePassword()
    {
        $profile = CrmUserManager::getCurrentProfile();

        if (!$profile) {
            return $this->error('Unable to resolve the current CRM user', 401, 'user_not_found');
        }

        $bundle = StandalonePasswordManager::regeneratePassword((int) $profile['id'], [
            'rotated_by_user_id' => get_current_user_id() ?: null,
        ]);

        if (!$bundle) {
            return $this->error('Unable to reset the password for this account', 500, 'password_rotation_failed');
        }

        return $this->success([
            'password' => $bundle['password'],
            'record' => $bundle['record'],
            'share' => $bundle['share'],
            'message' => 'Password reset successfully.',
        ], ['updated' => true]);
    }
}
