<?php

namespace App\Http\Controllers\Api\V1\Design;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Design\CalculateBomRequest;
use App\Http\Requests\Design\GetEstimateParametersRequest;
use App\Http\Requests\Design\SaveCompanyFormulaRequest;
use App\Services\Design\BomCalculationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BomCalculationController extends Controller
{
    protected BomCalculationService $bomCalculationService;

    public function __construct(BomCalculationService $bomCalculationService)
    {
        $this->bomCalculationService = $bomCalculationService;
    }

    public function getEstimateParameters(GetEstimateParametersRequest $request, int $modelId): JsonResponse
    {
        return ApiResponse::handle(function () use ($request, $modelId) {
            $companyName = $request->query('company_name');

            $result = $this->bomCalculationService->getEstimateParameters($modelId, $companyName);

            return [
                'success' => true,
                'data' => $result,
                'message' => __('message.fetched'),
            ];
        });
    }

    public function calculateBom(CalculateBomRequest $request, int $bomTemplateId): JsonResponse
    {
        return ApiResponse::handle(function () use ($request, $bomTemplateId) {
            $data = $request->validated();

            $result = $this->bomCalculationService->calculateBomEstimate(
                $bomTemplateId,
                $data['parameters'],
                $data['company_name'] ?? null
            );

            if (! $result['success']) {
                return [
                    'success' => false,
                    'message' => __('error.calculation_failed'),
                    'error' => $result['error'],
                ];
            }

            return [
                'success' => true,
                'data' => $result['data'],
                'message' => __('message.calculation.completed'),
            ];
        });
    }

    public function getCompanyFormulas(string $companyName): JsonResponse
    {
        return ApiResponse::handle(function () use ($companyName) {
            $result = $this->bomCalculationService->getCompanyFormulas($companyName);

            return [
                'success' => true,
                'data' => $result,
                'message' => __('message.fetched'),
            ];
        });
    }

    public function saveCompanyFormula(SaveCompanyFormulaRequest $request, string $companyName, string $formulaType): JsonResponse
    {
        return ApiResponse::handle(function () use ($request, $companyName, $formulaType) {
            $data = $request->validated();

            $result = $this->bomCalculationService->saveCompanyFormula($companyName, $formulaType, $data);

            return [
                'success' => true,
                'data' => $result,
                'message' => __('message.company_formula.created'),
            ];
        });
    }

    public function testFormula(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $request->validate([
                'formula_expression' => 'required|string',
                'test_parameters' => 'required|array',
            ]);

            $startTime = microtime(true);

            // 직접 FormulaParser를 사용하여 테스트
            $parser = app(\App\Services\Calculation\FormulaParser::class);
            $result = $parser->execute(
                $request->input('formula_expression'),
                $request->input('test_parameters')
            );

            $executionTime = (microtime(true) - $startTime) * 1000; // ms로 변환

            return [
                'success' => true,
                'data' => [
                    'formula_expression' => $request->input('formula_expression'),
                    'input_parameters' => $request->input('test_parameters'),
                    'result' => $result,
                    'execution_time_ms' => round($executionTime, 2),
                ],
                'message' => __('message.formula.test_completed'),
            ];
        });
    }
}
