<?php

namespace App\Services\Integrations\Tickets\Zendesk;

use App\Models\ApiCredential;
use App\Services\Integrations\Tickets\TicketIntegrationInterface;
use Facades\App\Services\Integrations\Tickets\Zendesk\OAuthWrapperZendesk;
use Illuminate\Support\Facades\Cache;

class ZendeskIntegration implements TicketIntegrationInterface
{
    /**
     * getTicket
     *
     * @param  string $ticketId
     * @return object
     */
    public function getTicket(string $ticketId)
    {
        $zendeskData = OAuthWrapperZendesk::getTicket($ticketId);
        return !empty($zendeskData['ticket']['id']) ? $zendeskData['ticket'] : null;
    }

    /**
     * createTicket
     *
     * @param  array $ticketData
     * @return object 
     */
    public function createTicket(array $ticketData)
    {
        $zendeskData = OAuthWrapperZendesk::createTicket($ticketData);

        return !empty($zendeskData['ticket']) ? $zendeskData['ticket'] : null;
    }

    /**
     * addCommentToTicket
     *
     * @param  string $requestId
     * @param  string $message
     * @param  string $userId
     * @return object
     */
    public function addCommentToTicket(string $ticketId, string $message, string $userId)
    {
        $comment = OAuthWrapperZendesk::addComment($ticketId, $message, $userId);
        return !empty($comment['ticket']);
    }

    /**
     * addAttachmentToTicket
     *
     * @param  string $requestId
     * @param  string $message
     * @param  string $userId
     * @return object
     */
    public function addAttachmentToTicket(string $ticketId, string $message, string $userId, $filePath, $fileName)
    {
        $upload = OAuthWrapperZendesk::addAttachment($ticketId, $message, $userId, $filePath, $fileName);
        if (isset($upload['upload']['token'])) {
            $attach = OAuthWrapperZendesk::addAttachmenttoComment($ticketId, $message, $userId, $upload['upload']['token']);
        }
        return !empty($upload['upload']['token']) ? $upload['upload']['token'] : null;
    }

    /**
     * Get the complete ticket url
     * @param string $requestId
     * 
     * @return [type]
     */
    public function getTicketUrl($requestId)
    {
        // Cache the Zendesk URL for 60 minutes (adjust the time as needed).
        $zendeskUrl = Cache::remember('zendesk_credential_url', 60, function () {
            return optional(OAuthWrapperZendesk::getApiCredential()->zendeskCredential)->url;
        });

        if ($zendeskUrl) {
            // Example URL: https://domain.zendesk.com/agent/tickets/7
            return $requestId ? '<a href="' . $zendeskUrl . 'agent/tickets/' . $requestId . '" target="_blank">' . $requestId . '</a>' : '';
        }

        return '';
    }
}
