<?php

namespace App\Actions\Terminals;

use App\Models\Terminal;
use App\Services\Excel\SpreadsheetWriter;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * Build a downloadable spreadsheet of every terminal.
 *
 * Extension points:
 *   - filter `terminals.export.header` → adjust the header row
 *   - filter `terminals.export.row`    → adjust each data row (row array + Terminal)
 *   - action `terminals.before_export` / `terminals.after_export`
 */
class ExportTerminals
{
    public function __construct(private SpreadsheetWriter $writer) {}

    public function __invoke(string $format = 'csv'): StreamedResponse
    {
        $format   = strtolower($format);
        $filename = 'terminals-'.now()->format('Y-m-d').".{$format}";

        $terminals = Terminal::query()->with('store')->ordered()->get();

        $header = apply_filters('terminals.export.header', [
            'ID',
            'Store',
            'Code',
            'Name',
            'Active',
            'Last seen',
            'Created at',
        ]);

        $rows = $terminals->map(function (Terminal $t) {
            $row = [
                (string) $t->id,
                (string) ($t->store?->name ?? ''),
                (string) $t->code,
                (string) $t->name,
                $t->is_active ? 'Yes' : 'No',
                optional($t->last_seen_at)->toDateTimeString() ?? '',
                optional($t->created_at)->toDateTimeString() ?? '',
            ];

            return apply_filters('terminals.export.row', $row, $t);
        })->all();

        $count = count($rows);

        do_action('terminals.before_export', $format, $count);

        $response = $this->writer->stream($filename, $header, function (callable $write) use ($rows) {
            $write($rows);
        });

        do_action('terminals.after_export', $format, $count);

        return $response;
    }
}
