<?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\DTO\AuthenticatedUserDto;
use MefisAssetBridgeCore\Interfaces\EndpointInterface;

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

    private string $uuid;

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

    /** @var string Error message for invalid parameters */
    private string $validationError = '';
    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 and password are 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;
        }
        if (strlen($params['password']) < 8) {
            $this->validationError = 'Password must be at least 8 characters long';
            return false;
        }
        return true;
    }

    /**
     * Send login 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);
        }

        // Prepare request data - framework agnostic
        $data = [
            'email' => $params['email'],
            'password' => $params['password'],
        ];

        $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 login request
        $response = $this->ApiClient->post('auth/login', $data);

        if ($response->isSuccess()) {
            // Convert response data to AuthenticatedUserDto
            try {
                $responseData = $response->getData();
                if (is_array($responseData)) {
                    $userData = AuthenticatedUserDto::fromArray($responseData);

                    // Return the DTO in the response
                    return ApiResponse::success(['user' => $userData], 'Login successful');
                }
            } catch (\Exception $e) {
                return ApiResponse::error('Invalid response format: ' . $e->getMessage());
            }
        } else {
            if($response->getMessage() == 'Unauthorized App') {
                $keyStore = $this->ApiClient->getKeyStore();
                $keyStore->deleteKeys($this->uuid);

                $response = ApiResponse::error('Unauthorized App');
            }
        }

        return $response;
    }
}