<?php

namespace App\Http\Controllers\API\Investor;

use App\Helpers\Helper;
use App\Http\Controllers\API\BaseApiController;
use App\Models\IncentiveApplication;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class IncentiveApplicationController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $applications = IncentiveApplication::where('user_id', $request->user()->id)
            ->with(['incentive:id,name,type', 'proposal:id,code,name'])
            ->orderByDesc('created_at')
            ->paginate(15);

        return $this->paginatedResponse($applications);
    }

    public function store(Request $request, int $incentiveId): JsonResponse
    {
        $request->validate([
            'proposal_id'   => 'nullable|exists:investment_proposals,id',
            'justification' => 'required|string|max:2000',
        ]);

        $existing = IncentiveApplication::where('user_id', $request->user()->id)
            ->where('incentive_id', $incentiveId)
            ->where('proposal_id', $request->proposal_id)
            ->first();

        if ($existing) {
            return $this->errorResponse('Já candidatou a este incentivo', 422);
        }

        $application = IncentiveApplication::create([
            'code'          => Helper::generateCode(10, 'incentive_applications'),
            'user_id'       => $request->user()->id,
            'incentive_id'  => $incentiveId,
            'proposal_id'   => $request->proposal_id,
            'justification' => $request->justification,
            'status'        => 'pendente',
        ]);

        return $this->successResponse($application, 'Candidatura enviada com sucesso', 201);
    }
}
