<?php

namespace App\Http\Controllers\API\Investor;

use App\Http\Controllers\API\BaseApiController;
use App\Models\FiscalIncentive;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class IncentiveController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $incentives = FiscalIncentive::where('is_active', true)
            ->when($request->type, fn($q) => $q->where('type', $request->type))
            ->orderBy('sort_order')
            ->get();

        return $this->successResponse($incentives);
    }

    public function simulate(Request $request): JsonResponse
    {
        $request->validate([
            'investment_value' => 'required|numeric|min:0',
            'sector'           => 'required|string',
            'province_code'    => 'nullable|string',
        ]);

        $applicable = FiscalIncentive::where('is_active', true)
            ->where(fn($q) =>
                $q->whereNull('min_investment')
                  ->orWhere('min_investment', '<=', $request->investment_value)
            )
            ->get()
            ->filter(function ($incentive) use ($request) {
                $sectorOk = !$incentive->eligible_sectors ||
                    in_array($request->sector, $incentive->eligible_sectors);
                $provinceOk = !$request->province_code ||
                    !$incentive->eligible_provinces ||
                    in_array($request->province_code, $incentive->eligible_provinces);
                return $sectorOk && $provinceOk;
            })
            ->map(fn($inc) => [
                ...$inc->toArray(),
                'estimated_benefit_usd' => round($request->investment_value * $inc->benefit_percentage / 100, 2),
            ])
            ->values();

        return $this->successResponse($applicable);
    }
}
