<?php

declare(strict_types=1);

namespace App\Exports;

use App\Models\AssetWarranty;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

/**
 * The warranty register as a spreadsheet, honouring the same filters as
 * `warranty.index` — "export" always means "export what I am looking at".
 */
class WarrantyExport implements FromQuery, ShouldAutoSize, WithHeadings, WithMapping
{
    /**
     * @param  array<string, mixed>  $filters
     */
    public function __construct(
        private readonly array $filters = [],
    ) {}

    public function query(): Builder
    {
        return AssetWarranty::query()
            ->with(['asset.category'])
            ->search($this->filters['search'] ?? null)
            ->ofType($this->filters['type'] ?? null)
            ->when(($this->filters['status'] ?? null) === 'expired', fn (Builder $q) => $q->expired())
            ->when(($this->filters['status'] ?? null) === 'active', fn (Builder $q) => $q->active())
            ->orderBy('end_date');
    }

    /**
     * @return array<int, string>
     */
    public function headings(): array
    {
        return [
            'Asset Tag',
            'Asset Name',
            'Type',
            'Provider',
            'Reference Number',
            'Start Date',
            'End Date',
            'Days Remaining',
            'Cost',
            'Status',
            'Primary',
        ];
    }

    /**
     * @param  AssetWarranty  $warranty
     * @return array<int, mixed>
     */
    public function map($warranty): array
    {
        return [
            $warranty->asset->asset_tag,
            $warranty->asset->name,
            $warranty->type->label(),
            $warranty->provider,
            $warranty->reference_number,
            $warranty->start_date->format('Y-m-d'),
            $warranty->end_date->format('Y-m-d'),
            $warranty->daysRemaining(),
            $warranty->cost,
            $warranty->status()->label(),
            $warranty->is_primary ? 'Yes' : 'No',
        ];
    }
}
