<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PayrollCycle;
use App\Services\AuditService;
use App\Services\Payroll\PayrollBankExportService;
use Symfony\Component\HttpFoundation\StreamedResponse;

class PayrollBankExportController extends Controller
{
    public function __construct(
        protected PayrollBankExportService $exportService,
        protected AuditService $audit
    ) {}

    public function download(PayrollCycle $cycle): StreamedResponse
    {
        abort_unless(auth()->user()?->hasPermission('payrolls_view'), 403);

        $companyId = auth()->user()?->company_id;
        if ($companyId && (int) $cycle->company_id !== (int) $companyId) {
            abort(403);
        }

        $this->audit->log('payroll.bank_export', $cycle, [
            'year' => $cycle->year,
            'month' => $cycle->month,
            'rows' => count($this->exportService->rowsForCycle($cycle)),
            'channel' => 'api',
        ]);

        return $this->exportService->downloadCsv($cycle);
    }
}
