<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Item;
use Illuminate\Http\Request;

class RecipeController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'parent_item_id' => 'required|exists:items,id',
            'child_item_id'  => 'required|exists:items,id|different:parent_item_id',
            'qty_needed'     => 'required|numeric|min:0.1',
        ]);

        // Cari item induk (contoh: Aren Syrup)
        $parentItem = Item::findOrFail($validated['parent_item_id']);

        // Gunakan relasi Eloquent untuk menyambungkan dengan anak (contoh: Aren Batok)
        // syncWithoutDetaching agar data sebelumnya tidak terhapus jika kita menambah bahan lain
        $parentItem->ingredients()->syncWithoutDetaching([
            $validated['child_item_id'] => ['qty_needed' => $validated['qty_needed']]
        ]);

        return response()->json([
            'status'  => 'success',
            'message' => 'Resep berhasil diikat',
        ], 201);
    }
}