<?php

namespace App\Services\Asset;

use App\Events\UpdateAssetStatus;
use App\Models\Asset;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Auth;
use Facades\App\Services\AssetHistory as RepoAssetHistory;
use Facades\App\Services\JiraDescription;

class UpdateAssigneeService
{

    /**
     * Update the assignee of an asset
     * 
     * @param array $inputData Data to update the asset
     * 
     * @return bool True if the update was successful
     */
    public function updateAssignee($inputData)
    {
        try {
            $asset = Asset::findOrFail($inputData['asset_id']);

            $data = [
                'user_id'   => $inputData['user_id'],
                'ticket_no' => $inputData['ticket_no'] ?? $asset->ticket_no
            ];

            $assetHistory = $this->getHistoryData($asset, $data, $inputData['comments'] ?? '');

            $jiraDescription = JiraDescription::getStatusDescription('UpdateAssignee', $data, $asset, $inputData['comments'] ?? '');

            event(new UpdateAssetStatus($jiraDescription, ($inputData['ticket_no'] ?? null), $assetHistory, Auth::user()->id));

            $asset->update($data);

            return true;
        } catch (Exception) {
            return false;
        }
    }

    /**
     * Prepares the asset history data for an assignee update.
     *
     * @param Asset $asset The asset model instance being updated.
     * @param array $data An array containing the new user_id and other details.
     * @param string|null $comments Optional comments about the update.
     *
     * @return array The formatted asset history data with the new and old user information,
     *               the update description, and other metadata.
     */
    private function getHistoryData($asset, $data, $comments = null)
    {
        $description = RepoAssetHistory::getStatusDescription('UpdateAssignee', $data, $asset, $comments);

        $data = [
            'user_id' => Auth::id(),
            'asset_id' => $asset->id,
            'ticket_no' => $asset->ticket_no,
            'ticket_service_provider' => config('ticket-integration.service'),
            'action' => 'user_updated',
            'comments' => $comments,
            'old_user_id' => $asset->user_id,
            'new_user_id' => $data['user_id'],
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        return $data;
    }
}
