<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Finance\FeeFamilyBalanceRequest;
use App\Http\Requests\Finance\FeeRefundRequest;
use App\Http\Requests\Finance\FeeTuitionBreakdownRequest;
use App\Http\Requests\Finance\FeeTuitionTotalRequest;
use App\Http\Resources\Fees\FeeFamilyBalanceResource;
use App\Http\Resources\Fees\FeeRefundResource;
use App\Http\Resources\Fees\FeeTuitionBreakdownResource;
use App\Http\Resources\Fees\FeeTuitionTotalResource;
use App\Services\Billing\BalanceCalculationService;
use App\Services\Fees\FeeRefundCalculatorService;
use App\Services\Fees\FeeStudentFeeService;
use App\Services\Fees\TuitionCalculationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class FeeCalculationController extends BaseApiController
{
    public function __construct(
        private FeeRefundCalculatorService $refunds,
        private FeeStudentFeeService $tuition,
        private TuitionCalculationService $tuitionCalculator,
        private BalanceCalculationService $balance
    ) {
        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,
            ]),
        ]);
    }

    public function tuitionBreakdown(FeeTuitionBreakdownRequest $request): JsonResponse
    {
        $payload = $request->validated();

        try {
            $result = $this->tuitionCalculator->calculate($payload['students']);
        } catch (\Throwable $e) {
            Log::error('Tuition breakdown calculation failed', [
                'exception' => $e,
            ]);

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

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

    public function familyBalance(FeeFamilyBalanceRequest $request): JsonResponse
    {
        $payload = $request->validated();

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

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

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