<?php

namespace App\Services\BulkUpload;

use Facades\App\Services\AssetHistory as AssetHistoryService;
use App\Events\BulkUpdates;
use Illuminate\Support\Facades\Auth;
use App\Models\Location;
use App\Models\Asset;
use App\Services\Integrations\Tickets\TicketManagementService;
use Illuminate\Support\Facades\Validator;

class SpecialBulkMoveService extends SpecialBulkAbstract
{

    /**
     * Class constructor.
     *
     * Initializes the class with a TicketManagementService instance.
     *
     * @param TicketManagementService $ticketManagementService The ticket management service instance.
     */
    public function __construct(protected TicketManagementService $ticketManagementService)
    {
    }

    /**
     * Retrieves the header map configuration for bulk uploads.
     *
     * @return array The header map configuration.
     */
    public function getHeaderMap()
    {
        return config('bulk-upload.moveData');
    }

    /**
     * Generates CSV data from the given item.
     *
     * @param array $item The item to process.
     *
     * @return array An array containing 'assetData' and 'errorData'.
     */
    public function generateCSVData(array $item)
    {
        if (empty($item)) {
            return false;
        }

        $assetData    = [];
        $errorData    = '';

        foreach ($this->getHeaderMap() as $dbField => $fileHeader) {
            $result = $this->getRelationalValues($item, $dbField, $fileHeader);

            if ($result == false) {
                if ($dbField == "location_id") {
                    $errorData .= 'Location ' . $item[$fileHeader] . ' do not exist.' . "\r\n";
                }

                if ($dbField == "user_id") {
                    $errorData .= 'User with email ' . trim($item[$fileHeader]) . ' do not exist.' . "\r\n";
                }
            }

            if ($result !== false) {
                $item[$fileHeader] = $result;
            }

            $assetData[$dbField] = !empty($item[$fileHeader]) ? $item[$fileHeader] : null;

            if ($dbField == "serial_no") {
                if (!empty($item[$fileHeader])) {
                    $asset = Asset::where('serial_no', trim($item[$fileHeader]))->first();

                    if ($asset) {
                        $assetData['id'] = $asset->id;
                    }

                    if (!$asset) {
                        $errorData .= 'Asset with serial # ' . $item[$fileHeader] . ' do not exist.' . "\r\n";
                    }
                }
            }
        }

        return compact('assetData', 'errorData');
    }

    /**
     * Saves the history of the given asset with the provided data.
     *
     * @param Asset $asset     The asset for which the history is being saved.
     * @param array $assetData The data related to the asset changes.
     *
     * @return void
     */
    public function saveAssetHistory(Asset $asset, array $assetData)
    {
        $comments = null;

        $description = __('history.Moved', [
            'assetname' => $asset->serial_no,
            'assetid' => $asset->id,
            'oldroomname' => optional($asset->location)->room_name,
            'newroomname' => optional(Location::findOrFail($assetData['location_id']))->room_name,
            'commenttext' => $comments,
        ]);

        $assetHistory = [
            'user_id' => Auth::id(),
            'asset_id' => $asset->id,
            'action' => 'moved',
            'old_location_id' => optional($asset->location)->id,
            'new_location_id' => $assetData['location_id'],
            'comments' => $comments,
            'old_value' => optional($asset->location)->room_name,
            'new_value' => optional(Location::findOrFail($assetData['location_id']))->room_name,
            'description' => $description,
            'ticket_no' => $assetData['ticket_no']
        ];

        $assetHistory = $this->getAdditionalHistoryData($assetHistory, $assetData, $asset);
        event(new BulkUpdates($assetHistory));
    }

    /**
     * Retrieves the status slug.
     *
     * @return string The status slug.
     */
    public function getStatusSlug()
    {
        return "";
    }

    /**
     * Retrieves specific data from the given asset.
     *
     * @param Asset $asset The asset instance from which to retrieve data.
     *
     * @return string The retrieved data.
     */
    public function getData(Asset $asset)
    {
        return "";
    }

    /**
     * Retrieves the default ticket configuration for bulk move operations.
     *
     * @return string The default ticket configuration.
     */
    public function getDefaultTicket()
    {
        return config('tickets.bulk_move');
    }

    /**
     * Attaches a file to the specified ticket.
     *
     * @param mixed  $ticketid The ID of the ticket to which the file will be attached.
     * @param string $filePath The path to the file to be attached.
     * @param string $fileName The name of the file to be attached.
     *
     * @return bool Returns true if the file was successfully attached, false otherwise.
     */
    public function attachFiletoTicket($ticketid, $filePath, $fileName)
    {
        if (!$ticketid || !$filePath || !$fileName) {
            return false;
        }

        $this->ticketManagementService->attachActionHistorytoTicket($ticketid, 'Bulk move (special)', Auth::user()->id, $filePath, $fileName);

        return true;
    }
}
