<?php

namespace App\Http\Controllers\Api\v1;

use App\Enums\ProductCategories;
use Illuminate\Http\Request;
use App\Models\Admin\Taxonomy;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\v1\Taxonomy\TaxonomyResource;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Http\Resources\Api\v1\Taxonomy\TaxonomyResourceCollection;

class TaxonomyController extends Controller
{

    public function __construct()
    {
        $acceptLanguage = request()->header('Accept-Language');
        app()->setLocale($acceptLanguage);
    }

    public function index(Request $request)
    {
        try {
            $mainCategoryId = $request->input('main_category_id');

            $validMainCategories = [
                ProductCategories::MARINE->value,
                ProductCategories::WATERWORKS->value,
                ProductCategories::MARITIME->value,
                ProductCategories::REMOTE->value
            ];

            if ($mainCategoryId && !in_array($mainCategoryId, $validMainCategories)) {
                return response()->json(['error' => 'Invalid main category id.', 'code' => 400], 400);
            }

            $subCategoryId = $request->input('sub_category_id');

            if ($subCategoryId !== null && $mainCategoryId) {
                $isChild = Taxonomy::where('id', $subCategoryId)
                                ->where('parent_id', $mainCategoryId)
                                ->exists();

                if (!$isChild) {
                    return response()->json(['error' => 'Invalid sub category id for the given main category', 'code' => 400], 400);
                }
            }

            $allMainCategories = Taxonomy::where('parent_id', 4)->get();

            $selectedCategory = null;

            if ($mainCategoryId) {
                $selectedCategory = Taxonomy::with('childrenRecursive')->find($mainCategoryId);
            }

            $categories = $allMainCategories->map(function ($category) use ($selectedCategory, $mainCategoryId) {
                if ($selectedCategory && $category->id == $mainCategoryId) {
                    return new TaxonomyResource($selectedCategory);
                }
                return new TaxonomyResource($category);
            });

            return new TaxonomyResourceCollection($categories, $mainCategoryId, $subCategoryId);
        }
        catch (ModelNotFoundException $e) {
            return response()->json(['error' => 'Category not found', 'code' => 404], 404);
        }
        catch (\Exception $e) {
            return response()->json(['error' => 'Failed to retrieve categories', 'code' => 500], 500);
        }
    }
}