<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\ListingFeature;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class FeatureController extends Controller
{
    private array $inputTypes = ['number', 'boolean', 'select', 'multiselect', 'text', 'date'];

    public function index()
    {
        $features = ListingFeature::query()
            ->orderBy('sort_order')
            ->get()
            ->map(fn ($f) => $this->toArray($f));

        return response()->json(['data' => $features]);
    }

    public function store(Request $request)
    {
        $data = $this->validateData($request);

        $feature = ListingFeature::create([
            // Tek dilli girilen ad iki locale'e de yazılır; yoksa diğer dilde
            // görüntülenen ilanlarda özellik adı boş kalıyordu.
            'name' => ['en' => $data['name'], 'tr' => $data['name']],
            'key' => $data['key'] ?? $this->uniqueKey($data['name']),
            'input_type' => $data['input_type'],
            'unit' => $data['unit'] ?? null,
            'options' => $this->normalizeOptions($data),
            'option_labels' => $this->normalizeOptionLabels($data, $data['input_type']),
            'is_filterable' => $data['is_filterable'] ?? false,
            'is_active' => $data['is_active'] ?? true,
            'sort_order' => $data['sort_order'] ?? 0,
        ]);

        return response()->json(['data' => $this->toArray($feature)], 201);
    }

    public function show(ListingFeature $feature)
    {
        return response()->json(['data' => $this->toArray($feature)]);
    }

    public function update(Request $request, ListingFeature $feature)
    {
        $data = $this->validateData($request, $feature->id);

        $resolvedType = $data['input_type'] ?? $feature->input_type;

        $feature->update([
            // Güncellemede de ad iki locale'e yazılır (admin formu tek dilli).
            'name' => isset($data['name'])
                ? ['en' => $data['name'], 'tr' => $data['name']]
                : $feature->getTranslations('name'),
            'key' => $data['key'] ?? $feature->key,
            'input_type' => $resolvedType,
            'unit' => array_key_exists('unit', $data) ? $data['unit'] : $feature->unit,
            'options' => array_key_exists('options', $data) ? $this->normalizeOptions($data) : $feature->options,
            'option_labels' => array_key_exists('option_labels', $data)
                ? $this->normalizeOptionLabels($data, $resolvedType)
                : $feature->getTranslations('option_labels'),
            'is_filterable' => $data['is_filterable'] ?? $feature->is_filterable,
            'is_active' => $data['is_active'] ?? $feature->is_active,
            'sort_order' => $data['sort_order'] ?? $feature->sort_order,
        ]);

        return response()->json(['data' => $this->toArray($feature->fresh())]);
    }

    public function destroy(ListingFeature $feature)
    {
        if ($feature->values()->exists()) {
            return response()->json([
                'message' => 'Bu özellik ilanlarda kullanılıyor, silinemez.',
            ], 422);
        }

        $feature->delete();

        return response()->json(['message' => 'Özellik silindi.']);
    }

    private function validateData(Request $request, ?int $ignoreId = null): array
    {
        return $request->validate([
            'name' => [$ignoreId ? 'sometimes' : 'required', 'string', 'max:255'],
            'key' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9_]+$/', Rule::unique('listing_features', 'key')->ignore($ignoreId)],
            'input_type' => [$ignoreId ? 'sometimes' : 'required', Rule::in($this->inputTypes)],
            'unit' => ['nullable', 'string', 'max:50'],
            'options' => ['nullable', 'array'],
            'options.*' => ['string', 'max:255'],
            // option_labels: {locale: {canonical: label}} — seçenek etiketi çevirileri.
            'option_labels' => ['nullable', 'array'],
            'is_filterable' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer'],
        ]);
    }

    /** select/multiselect dışındaki tiplerde options'ı null'a çeker. */
    private function normalizeOptions(array $data): ?array
    {
        $type = $data['input_type'] ?? null;
        if (! in_array($type, ['select', 'multiselect'], true)) {
            return null;
        }
        return $data['options'] ?? [];
    }

    /** option_labels'ı yalnızca select/multiselect için saklar. */
    private function normalizeOptionLabels(array $data, ?string $type): ?array
    {
        if (! in_array($type, ['select', 'multiselect'], true)) {
            return null;
        }
        return $data['option_labels'] ?? null;
    }

    private function toArray(ListingFeature $feature): array
    {
        return [
            'id' => $feature->id,
            'name' => $feature->name,
            // Admin EN/TR düzenlemesi için tam çeviri yapıları.
            'name_translations' => $feature->getTranslations('name'),
            'key' => $feature->key,
            'input_type' => $feature->input_type,
            'unit' => $feature->unit,
            'options' => $feature->options,
            'option_labels' => $feature->getTranslations('option_labels') ?: null,
            'is_filterable' => $feature->is_filterable,
            'is_active' => $feature->is_active,
            'sort_order' => $feature->sort_order,
        ];
    }

    private function uniqueKey(string $name): string
    {
        $base = Str::slug($name, '_') ?: 'feature';
        $key = $base;
        $i = 1;
        while (ListingFeature::where('key', $key)->exists()) {
            $key = "{$base}_{$i}";
            $i++;
        }
        return $key;
    }
}
