<?php

namespace App\Http\Controllers;

use App\Models\ProductTag;
use App\Http\Requests\Product\ProductTagRequest;
use App\Http\Resources\ProductResource;
use Illuminate\Support\Arr;

class ProductTagController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $productTags = ProductTag::with(['product', 'tag'])->get();
        return \SuccessData(__('public.Show'), $productTags);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(ProductTagRequest $request)
    {
        try {
            $productTag = Arr::only($request->validated(), ['product_id', 'tag_id']);
            ProductTag::create($productTag);
            return \Success(__('public.Create'));
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Product tag creation failed: ' . $e->getMessage(),
                'code' => 500,
                'data' => null,
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(ProductTag $productTag)
    {
        $products = $productTag->tag->products;
        return \SuccessData(__('public.Show'), ProductResource::collection($products));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ProductTagRequest $request, ProductTag $productTag)
    {
        try {
            $productTag->update($request->validated());
            return \SuccessData(__('public.Update'), $productTag->load(['product', 'tag']));
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Product tag update failed: ' . $e->getMessage(),
                'code' => 500,
                'data' => null,
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(ProductTag $productTag)
    {
        try {
            $productTag->delete();
            return \Success(__('public.Delete'));
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Product tag deletion failed: ' . $e->getMessage(),
                'code' => 500,
                'data' => null,
            ], 500);
        }
    }
}
