<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Finance\CarryforwardAdjustmentRequest;
use App\Http\Requests\Finance\CarryforwardFinalizeRequest;
use App\Http\Requests\Finance\CarryforwardPreviewRequest;
use App\Services\Finance\PriorYearBalanceCarryforwardService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class BalanceCarryforwardController extends Controller
{
    public function __construct(private PriorYearBalanceCarryforwardService $service) {}

    public function preview(CarryforwardPreviewRequest $request): JsonResponse
    {
        return response()->json(['ok' => true, 'preview' => $this->service->preview($request->validated())]);
    }

    public function storeDraft(CarryforwardFinalizeRequest $request): JsonResponse
    {
        return response()->json(['ok' => true, 'result' => $this->service->storeDrafts($request->validated(), optional($request->user())->id)]);
    }

    public function approve(Request $request, int $carryforward): JsonResponse
    {
        return response()->json(['ok' => true, 'carryforward' => $this->service->approve($carryforward, optional($request->user())->id)]);
    }

    public function postToNewYear(Request $request, int $carryforward): JsonResponse
    {
        return response()->json(['ok' => true, 'carryforward' => $this->service->postToNewYear($carryforward, optional($request->user())->id)]);
    }

    public function waive(CarryforwardAdjustmentRequest $request, int $carryforward): JsonResponse
    {
        $data = $request->validated();
        return response()->json(['ok' => true, 'carryforward' => $this->service->waive($carryforward, (float) $data['amount'], $data['reason'] ?? null, optional($request->user())->id)]);
    }

    public function adjust(CarryforwardAdjustmentRequest $request, int $carryforward): JsonResponse
    {
        $data = $request->validated();
        return response()->json(['ok' => true, 'carryforward' => $this->service->adjust($carryforward, (float) $data['amount'], $data['reason'] ?? null)]);
    }

    public function report(Request $request): JsonResponse
    {
        return response()->json(['ok' => true, 'report' => $this->service->report($request->query())]);
    }

    public function reportCsv(Request $request): StreamedResponse
    {
        $rows = $this->service->csvRows($this->service->report($request->query()));
        return response()->streamDownload(function () use ($rows) {
            $out = fopen('php://output', 'w');
            foreach ($rows as $row) fputcsv($out, $row);
            fclose($out);
        }, 'carryforward_report_' . date('Ymd_His') . '.csv', ['Content-Type' => 'text/csv']);
    }
}
