<?php

namespace App\Filament\Exports;

use App\Models\Catalog\Product;
use App\Services\BatchService;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
use Illuminate\Support\Number;

/**
 * Columns mirror ProductResource::table() exactly. Price is a property of the
 * receipt lots, so the Sale price column is the range across the product's
 * sellable lots (one number when they agree), not a stored product price.
 */
class ProductExporter extends Exporter
{
    protected static ?string $model = Product::class;

    /** @var array<int, array{price_min: float, price_max: float, lot_count: int}>|null */
    private static ?array $priceRanges = null;

    public static function getColumns(): array
    {
        return [
            ExportColumn::make('sku')->label('SKU'),
            ExportColumn::make('name'),
            ExportColumn::make('mainCategory.name')->label('Category'),
            ExportColumn::make('price')
                ->label('Sale price')
                ->state(fn (Product $record): ?string => static::rangeLabel((int) $record->id)),
            ExportColumn::make('is_active')->label('Active'),
        ];
    }

    private static function rangeLabel(int $productId): ?string
    {
        if (self::$priceRanges === null) {
            $ids = Product::query()->pluck('id')->map(fn ($id) => (int) $id)->all();
            self::$priceRanges = app(BatchService::class)->priceRangesFor($ids, null);
        }

        $range = self::$priceRanges[$productId] ?? null;
        if (! $range) {
            return null;
        }

        $min = (float) $range['price_min'];
        $max = (float) $range['price_max'];

        return $min === $max ? number_format($min, 2) : number_format($min, 2).' – '.number_format($max, 2);
    }

    public static function getCompletedNotificationBody(Export $export): string
    {
        $body = 'Your product export has completed and '.Number::format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.';

        if ($failedRowsCount = $export->getFailedRowsCount()) {
            $body .= ' '.Number::format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.';
        }

        return $body;
    }
}
