<?php

namespace App\Services;

use App\Helpers\AmountInWords;
use App\Helpers\CompanyMedia;
use App\Helpers\GstHelper;
use App\Helpers\CompanySettings;
use App\Helpers\QuotationDocumentSettings;
use App\Models\Company;
use App\Models\Quotation;
use App\Models\TaxRate;

class QuotationDocumentPresenter
{
    /**
     * @return array<string, mixed>
     */
    public function displayData(Quotation $quotation): array
    {
        $quotation->load(['items', 'customer']);
        $company = Company::findOrFail($quotation->company_id);
        $taxRates = TaxRate::where('company_id', $company->id)->active()->selectable()->get();

        $settings = CompanySettings::forCompany($company->id);
        $docSettings = QuotationDocumentSettings::forCompany($company->id);

        $gstContext = GstHelper::documentViewContext($company, $quotation);

        return array_merge([
            'quotation' => $quotation,
            'company' => $company,
            'settings' => $settings,
            'docSettings' => $docSettings,
            'taxBreakdown' => $gstContext['gstMode']
                ? []
                : $this->buildTaxBreakdown($quotation, $taxRates),
            'amountInWords' => AmountInWords::rupees((float) $quotation->grand_total),
            'documentCopies' => QuotationDocumentSettings::documentCopies($company->id),
            'quotationTitle' => QuotationDocumentSettings::titleForType($quotation->type, $company->id),
            'logoSrc' => CompanyMedia::imageSource($company->logo_path),
            'signatureSrc' => CompanyMedia::imageSource($company->signature_image_path),
        ], $gstContext);
    }

    /**
     * @return list<array{name: string, rate: float, amount: float}>
     */
    private function buildTaxBreakdown(Quotation $quotation, $taxRates): array
    {
        $groups = [];

        foreach ($quotation->items as $line) {
            if ((float) $line->tax_amount <= 0) {
                continue;
            }

            $rate = (float) $line->tax_rate;
            $key = number_format($rate, 2, '.', '');

            if (! isset($groups[$key])) {
                $tax = $taxRates->first(fn ($t) => abs((float) $t->rate - $rate) < 0.001);
                $groups[$key] = [
                    'name' => $tax?->name ?? 'Tax',
                    'rate' => $rate,
                    'amount' => 0,
                ];
            }

            $groups[$key]['amount'] += (float) $line->tax_amount;
        }

        usort($groups, fn ($a, $b) => $a['rate'] <=> $b['rate']);

        return array_values($groups);
    }
}
