<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Finance\FeeRefundRequest;
use App\Http\Requests\Finance\FeeTuitionTotalRequest;
use App\Http\Resources\Fees\FeeRefundResource;
use App\Http\Resources\Fees\FeeTuitionTotalResource;
use App\Services\Fees\FeeRefundCalculatorService;
use App\Services\Fees\FeeStudentFeeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class FeeCalculationController extends BaseApiController
{
    public function __construct(
        private FeeRefundCalculatorService $refunds,
        private FeeStudentFeeService $tuition
    ) {
        parent::__construct();
    }

    public function refund(FeeRefundRequest $request): JsonResponse
    {
        $payload = $request->validated();

        try {
            $result = $this->refunds->calculateRefund($payload['students'], (int) $payload['parent_id']);
        } catch (\Throwable $e) {
            Log::error('Fee refund calculation failed', [
                'parent_id' => $payload['parent_id'] ?? null,
                'exception' => $e,
            ]);

            return response()->json([
                'ok' => false,
                'message' => 'Unable to calculate refund.',
            ], 500);
        }

        return response()->json([
            'ok' => true,
            'refund' => new FeeRefundResource($result),
        ]);
    }

    public function tuitionTotal(FeeTuitionTotalRequest $request): JsonResponse
    {
        $payload = $request->validated();

        try {
            $total = $this->tuition->totalTuitionFee($payload['students']);
        } catch (\Throwable $e) {
            Log::error('Fee tuition total calculation failed', [
                'exception' => $e,
            ]);

            return response()->json([
                'ok' => false,
                'message' => 'Unable to calculate tuition total.',
            ], 500);
        }

        return response()->json([
            'ok' => true,
            'tuition' => new FeeTuitionTotalResource([
                'total_tuition' => $total,
            ]),
        ]);
    }
}
