<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\GiftTier;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GiftTierController extends Controller
{
    private function withProduct($query)
    {
        return $query->with(['product:id,name,slug,price']);
    }

    // Public: active tiers ordered by threshold
    public function index(): JsonResponse
    {
        $tiers = $this->withProduct(GiftTier::where('is_active', true)->orderBy('threshold'))->get();
        return response()->json(['data' => $tiers]);
    }

    // Admin: all tiers
    public function adminIndex(): JsonResponse
    {
        $tiers = $this->withProduct(GiftTier::orderBy('threshold'))->get();
        return response()->json(['data' => $tiers]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'threshold'   => 'required|numeric|min:0',
            'name'        => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'is_active'   => 'boolean',
            'sort_order'  => 'integer',
            'product_id'  => 'nullable|exists:products,id',
        ]);
        $tier = GiftTier::create($data);
        $tier->load('product:id,name,slug,price');
        return response()->json(['data' => $tier], 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $tier = GiftTier::findOrFail($id);
        $data = $request->validate([
            'threshold'   => 'sometimes|numeric|min:0',
            'name'        => 'sometimes|string|max:255',
            'description' => 'nullable|string|max:255',
            'is_active'   => 'boolean',
            'sort_order'  => 'integer',
            'product_id'  => 'nullable|exists:products,id',
        ]);
        $tier->update($data);
        $tier->load('product:id,name,slug,price');
        return response()->json(['data' => $tier]);
    }

    public function destroy(int $id): JsonResponse
    {
        GiftTier::findOrFail($id)->delete();
        return response()->json(['message' => 'Deleted.']);
    }
}
