<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Items\Item;
use App\Services\FormulaApiService;
use App\Services\ItemManagementService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ItemManagementApiController extends Controller
{
    public function __construct(
        private readonly ItemManagementService $service
    ) {}

    /**
     * 품목 목록 (HTML partial - 좌측 패널)
     */
    public function index(Request $request): View
    {
        $items = $this->service->getItemList([
            'search' => $request->input('search'),
            'item_type' => $request->input('item_type'),
            'per_page' => $request->input('per_page', 50),
        ]);

        return view('item-management.partials.item-list', compact('items'));
    }

    /**
     * BOM 재귀 트리 (JSON - 중앙 패널, JS 렌더링)
     */
    public function bomTree(int $id, Request $request): JsonResponse
    {
        $maxDepth = $request->input('max_depth', 10);
        $tree = $this->service->getBomTree($id, $maxDepth);

        return response()->json($tree);
    }

    /**
     * 품목 상세 (HTML partial - 우측 패널)
     */
    public function detail(int $id): View
    {
        $data = $this->service->getItemDetail($id);

        return view('item-management.partials.item-detail', [
            'item' => $data['item'],
            'bomChildren' => $data['bom_children'],
        ]);
    }

    /**
     * 수식 기반 BOM 산출 (API 서버의 FormulaEvaluatorService HTTP 호출)
     */
    public function calculateFormula(Request $request, int $id): JsonResponse
    {
        $item = Item::withoutGlobalScopes()
            ->where('tenant_id', session('selected_tenant_id'))
            ->findOrFail($id);

        $width = (int) $request->input('width', 1000);
        $height = (int) $request->input('height', 1000);
        $qty = (int) $request->input('qty', 1);
        $mp = $request->input('mp', 'single');

        $variables = [
            'W0' => $width,
            'H0' => $height,
            'QTY' => $qty,
            'MP' => in_array($mp, ['single', 'three']) ? $mp : 'single',
        ];

        // 제품모델/설치타입/마감타입 (입력값이 있으면 전달)
        if ($request->filled('product_model')) {
            $variables['product_model'] = $request->input('product_model');
        }
        if ($request->filled('installation_type')) {
            $variables['installation_type'] = $request->input('installation_type');
        }
        if ($request->filled('finishing_type')) {
            $variables['finishing_type'] = $request->input('finishing_type');
        }

        $formulaService = new FormulaApiService;
        $result = $formulaService->calculateBom(
            $item->code,
            $variables,
            (int) session('selected_tenant_id')
        );

        return response()->json($result);
    }
}
