<?php

namespace App\Http\Controllers\Api\V1\Admin\Settlement;

use App\Models\SettlementBatch;
use Symfony\Component\HttpFoundation\StreamedResponse;

final class AdminSettlementBatchExportController
{
    public function __invoke(SettlementBatch $batch): StreamedResponse
    {
        $batch->load(['draw:id,draw_no']);
        $filename = 'settlement-'.$batch->id.'-'.($batch->draw?->draw_no ?? 'draw').'.csv';

        return response()->streamDownload(function () use ($batch): void {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['ticket_no', 'play_code', 'player_id', 'matched_prize_tier', 'win_amount', 'jackpot_amount', 'match_detail']);
            $batch->details()->with('ticketItem')->orderBy('id')->chunk(200, function ($rows) use ($out): void {
                foreach ($rows as $row) {
                    fputcsv($out, [
                        $row->ticketItem?->ticket_no,
                        $row->ticketItem?->play_code,
                        $row->ticketItem?->player_id,
                        $row->matched_prize_tier,
                        (int) $row->win_amount,
                        (int) $row->jackpot_allocation_amount,
                        json_encode($row->match_detail_json, JSON_UNESCAPED_UNICODE),
                    ]);
                }
            });
            fclose($out);
        }, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']);
    }
}
