<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Faq;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class FaqController extends Controller
{
    // Panel listesi: taslaklar dahil tüm kayıtlar, gösterim sırasına göre.
    public function index()
    {
        $faqs = Faq::query()
            ->orderBy('order')
            ->orderBy('id')
            ->get()
            ->map(fn (Faq $faq) => $this->toArray($faq))
            ->values();

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

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

        $faq = Faq::create($data);

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

    public function update(Request $request, Faq $faq)
    {
        $data = $this->validateData($request, updating: true);

        $faq->update($data);

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

    public function destroy(Faq $faq)
    {
        $faq->delete();

        return response()->json([
            'message' => 'Faq silindi',
        ]);
    }

    /**
     * Soru/cevap iki dilli {tr, en} objesi olarak gelir; canlıda tek dilli
     * içerik kalmasın diye iki çeviri de zorunludur.
     */
    private function validateData(Request $request, bool $updating = false): array
    {
        $presence = $updating ? 'sometimes' : 'required';

        return $request->validate([
            'question' => [$presence, 'array'],
            'question.tr' => ['required_with:question', 'string', 'max:500'],
            'question.en' => ['required_with:question', 'string', 'max:500'],

            'answer' => [$presence, 'array'],
            'answer.tr' => ['required_with:answer', 'string', 'max:5000'],
            'answer.en' => ['required_with:answer', 'string', 'max:5000'],

            'order' => [$presence, 'integer', 'min:0', 'max:15'],
            'status' => [$presence, Rule::in([
                Faq::STATUS_DRAFT,
                Faq::STATUS_PUBLISHED,
            ])],
        ]);
    }

    private function toArray(Faq $faq): array
    {
        return [
            'id' => $faq->id,
            'question' => $faq->getTranslations('question'),
            'answer' => $faq->getTranslations('answer'),
            'order' => $faq->order,
            'status' => $faq->status,
        ];
    }
}
