<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  MefisAssetBridgeCore_Api_Endpoints
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

namespace MefisAssetBridgeCore\Api\Endpoints;

use MefisAssetBridgeCore\Api\ApiClient;
use MefisAssetBridgeCore\Auth\AuthenticatedUser;
use MefisAssetBridgeCore\Api\Response\ApiResponse;
use MefisAssetBridgeCore\Interfaces\EndpointInterface;

/**
 * Reset API Endpoint
 */
class Reset implements EndpointInterface
{
    /** @var ApiClient API client instance */
    private ApiClient $ApiClient;

    /** @var array Required parameters */
    private array $requiredParams = ['email'];

    private string $validationError = '';
    private string $uuid;
    private string $pathHash;

    public function __construct(string $uuid, ApiClient $ApiClient, ?AuthenticatedUser $user, string $pathHash = '')
    {
        $this->ApiClient = $ApiClient;
        $this->uuid = $uuid;
        $this->pathHash = $pathHash;
    }

    /**
     * Validate request parameters
     *
     * @param array $params Request parameters
     * @return bool True if parameters are valid
     */
    public function validateParams(array $params): bool
    {
        foreach ($this->requiredParams as $param) {
            if (empty($params[$param])) {
                $this->validationError = 'email field is required';
                return false;
            }
        }

        // email max 191 characters long
        if(mb_strlen($params['email']) > 191) {
            $this->validationError = 'Email cannot be longer than 191 characters';
            return false;
        }

        if (!filter_var($params['email'], FILTER_VALIDATE_EMAIL)) {
            $this->validationError = 'Please check your email address';
            return false;
        }

        return true;
    }

    /**
     * Send register request
     *
     * @param array $params Request parameters
     * @return ApiResponse
     */
    public function sendRequest(array $params): ApiResponse
    {
        // Validate required parameters
        if (!$this->validateParams($params)) {
            return ApiResponse::error($this->validationError);
        }

        // Create registration data - framework agnostic
        $data = [
            'email' => $params['email'],
        ];

        $data['website_id'] = $this->uuid;
        $data['path'] = $this->pathHash;

        $data['device_info'] = $this->ApiClient->getDeviceInfo();
        $data['domain'] = $this->ApiClient->getDomain();
        $data['cms_user_id'] = $this->ApiClient->getCMSUserId();
        $data['cms_version'] = $this->ApiClient->getCMSVersion();
        $data['cms_type'] = $this->ApiClient->getCMSType();

        // Send the registration request
        $response = $this->ApiClient->post('auth/reset', $data);

        if ($response->isSuccess()) {
            return ApiResponse::success(
                $response->getData(),
                'Reset successful',
                $response->getStatusCode()
            );
        }

        // If there was an error, return it with the error message
        return ApiResponse::error(
            $response->getMessage() ?: 'Reset failed',
            $response->getData(),
            $response->getStatusCode()
        );
    }
}