<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Jobs\Commands\V2\ProcessSalesInvoiceReportV2CommandJob;
use App\Classes\Modules\Bookings\DataTransferObjects\UpdateBookingSalesInvoiceDTO;
use App\Classes\Modules\Bookings\Standards\Rules\CanUpdateBookingSalesInvoice;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UpdateBatchBookingSalesInvoiceLogic extends AbstractControllerLogic
{

  /**
     * @return array
     */
    protected function notification(): array
    {
        return [
            'title' => 'Updated Bookings with Sales Invoices',
            'message' => 'You have successfully updated multiple bookings with Sales Invoices',
        ];
    }

    /** @var CanUpdateBookingSalesInvoice */
    private $canUpdateBookingSalesInvoice;

    /**
     * UpdateBatchBookingSalesInvoiceLogic constructor.
     * @param CanUpdateBookingSalesInvoice $canUpdateBookingSalesInvoice
     */
    public function __construct(
        CanUpdateBookingSalesInvoice $canUpdateBookingSalesInvoice
    ) {
        $this->canUpdateBookingSalesInvoice = $canUpdateBookingSalesInvoice;
    }

    /**
     * Handles batch update for multiple booking sales invoices
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request): JsonResponse
    {
        $collections = $request->input('collections', []);

        if (!is_array($collections) || empty($collections)) {
            return response()->json([
                'error' => 'Invalid or empty collections array provided.'
            ], 400);
        }

        $jobs = [];
        $processed = [];

        foreach ($collections as $index => $bookingData) {
            try {
                $data = [
                    'docno' => $bookingData['docno'] ?? $bookingData['DocNo'] ?? null,
                    'docdate' => $bookingData['docdate'] ?? $bookingData['DocDate'] ?? null,
                    'debtorcode' => $bookingData['debtorcode'] ?? $bookingData['DebtorCode'] ?? null,
                    'ref' => $bookingData['ref'] ?? $bookingData['Ref'] ?? null,
                    'shipinfo' => $bookingData['shipinfo'] ?? $bookingData['ShipInfo'] ?? null,
                    'accno' => $bookingData['accno'] ?? $bookingData['AccNo'] ?? null,
                    'detaildescription' => $bookingData['detaildescription'] ?? $bookingData['DetailDescription'] ?? null,
                    'furtherdescription' => $bookingData['furtherdescription'] ?? $bookingData['FurtherDescription'] ?? null,
                    'classification' => $bookingData['classification'] ?? $bookingData['Classification'] ?? null,
                    'deptno' => $bookingData['deptno'] ?? $bookingData['DeptNo'] ?? null,
                    'qty' => $bookingData['qty'] ?? $bookingData['Qty'] ?? null,
                    'unitprice' => $bookingData['unitprice'] ?? $bookingData['UnitPrice'] ?? null,
                    'submiteinvoice' => $bookingData['submiteinvoice'] ?? $bookingData['SubmitEinvoice'] ?? null,
                    'consolidatedeinvoice' => $bookingData['consolidatedeinvoice'] ?? $bookingData['ConsolidatedEinvoice'] ?? null,
                    'einvoicevalidationlink' => $bookingData['einvoicevalidationlink'] ?? $bookingData['EInvoiceValidationLink'] ?? null,
                ];

                $dto = new UpdateBookingSalesInvoiceDTO($data);
                $this->canUpdateBookingSalesInvoice->passes($dto);

                ProcessSalesInvoiceReportV2CommandJob::dispatch($dto->toArray());

            } catch (\Throwable $e) {
                Log::error("Failed to process booking at index {$index}: " . $e->getMessage());
            }
        }

        return $this->response([]);
    }
}
