<?php

namespace App\Http\Resources;

use App\Http\Resources\Traits\BuildsDealTitle;
use App\Traits\FormatAsCurrency;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\DealBuilder\Deal;

class DealList extends JsonResource
{
    use FormatAsCurrency;
    use BuildsDealTitle;

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $this->resource->through(fn(Deal $deal) => $this->mapDeal($deal));
        $resource = $this->resource->toArray();
        $resource['default_columns'] = [
            'status',
        ];
        return $resource;
    }

    private function mapDeal(Deal $deal)
    {
        $paymentTypeLabels = [
            'enquiry' => 'Enquiry',
            'reservation' => 'Reservation',
            'deposit' => 'Deposit',
            'full_payment' => 'Full Payment',
        ];

        $paymentTypeValue = $deal->payment_type?->value;
        $paymentType = $paymentTypeLabels[$paymentTypeValue] ?? ucfirst($paymentTypeValue ?? 'Unknown');
        $paidAmount = $deal->invoices()->where('status', 'paid')->sum('amount');
        $paidAmountFormatted = $this->asCurrency($paidAmount, null, 2);

        $description = collect([
            $paymentType,
            'Paid: ' . $paidAmountFormatted,
        ])->implode(' | ');

        return [
            'image' => [
                'src' => $deal->vehicle?->getPreviewImage('mini-thumb'),
                'alt' => $deal->vehicle?->title,
            ],
            'title' => $this->buildDealTitle($deal),
            'description' => $description,
            'metaItems' => [
                'status' => $deal->status?->name ?? __('labels.unknown_status'),
            ],
            'link' => '/manage-content/deals/edit/' . $deal->id,
            'uuid' => $deal->reference,
            'id' => $deal->id,
        ];
    }
}
