<?php

namespace App\Http\Controllers\Api\Admin;

use App\Actions\Page\CreatePageAction;
use App\Actions\Page\DeletePageAction;
use App\Actions\Page\UpdatePageAction;
use App\DTOs\PageData;
use App\Http\Controllers\Controller;
use App\Http\Requests\Page\StorePageRequest;
use App\Http\Requests\Page\UpdatePageRequest;
use App\Http\Resources\PageResource;
use App\Models\Page;
use App\Repositories\Contracts\PageRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\DB;
use OpenApi\Attributes as OA;

class PageController extends Controller
{
    public function __construct(private PageRepositoryInterface $repository) {}

    #[OA\Get(
        path: '/api/admin/pages',
        summary: 'Sayfaları listele (Admin)',
        tags: ['Admin - Pages'],
        security: [['sanctum' => []]],
        parameters: [
            new OA\Parameter(name: 'search', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'per_page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 15)),
        ],
        responses: [new OA\Response(response: 200, description: 'Sayfa listesi')],
    )]
    public function index(Request $request): AnonymousResourceCollection
    {
        $pages = $this->repository->paginate(
            $request->only(['search']),
            $request->integer('per_page', 15),
        );

        return PageResource::collection($pages);
    }

    #[OA\Post(
        path: '/api/admin/pages',
        summary: 'Yeni sayfa oluştur',
        tags: ['Admin - Pages'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(required: true, content: new OA\JsonContent(
            required: ['title', 'slug'],
            properties: [
                new OA\Property(property: 'title', type: 'string'),
                new OA\Property(property: 'slug', type: 'string'),
                new OA\Property(property: 'content', type: 'string'),
                new OA\Property(property: 'template', type: 'string'),
                new OA\Property(property: 'is_active', type: 'boolean'),
                new OA\Property(property: 'meta_title', type: 'string'),
                new OA\Property(property: 'meta_description', type: 'string'),
                new OA\Property(property: 'blocks', type: 'array', items: new OA\Items(
                    properties: [
                        new OA\Property(property: 'type', type: 'string'),
                        new OA\Property(property: 'content', type: 'object'),
                        new OA\Property(property: 'order_index', type: 'integer'),
                    ],
                )),
            ],
        )),
        responses: [
            new OA\Response(response: 201, description: 'Sayfa oluşturuldu'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function store(StorePageRequest $request, CreatePageAction $action): JsonResponse
    {
        return DB::transaction(function () use ($request, $action) {
            $validated = $request->validated();
            $blocks = $validated['blocks'] ?? [];
            unset($validated['blocks']);

            $dto = PageData::fromArray($validated);
            $page = $action->execute($dto);

            foreach ($blocks as $index => $block) {
                $page->blocks()->create([
                    'type' => $block['type'],
                    'content' => $block['content'],
                    'order_index' => $block['order_index'] ?? $index,
                ]);
            }

            return response()->json(new PageResource($page->load('blocks')), 201);
        });
    }

    #[OA\Get(
        path: '/api/admin/pages/{page}',
        summary: 'Sayfa detayı (Admin)',
        tags: ['Admin - Pages'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'page', in: 'path', required: true, schema: new OA\Schema(type: 'integer'))],
        responses: [new OA\Response(response: 200, description: 'Sayfa detayı')],
    )]
    public function show(Page $page): JsonResponse
    {
        return response()->json(new PageResource($page->load('blocks')));
    }

    #[OA\Put(
        path: '/api/admin/pages/{page}',
        summary: 'Sayfa güncelle',
        tags: ['Admin - Pages'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'page', in: 'path', required: true, schema: new OA\Schema(type: 'integer'))],
        requestBody: new OA\RequestBody(required: true, content: new OA\JsonContent(
            properties: [
                new OA\Property(property: 'title', type: 'string'),
                new OA\Property(property: 'slug', type: 'string'),
                new OA\Property(property: 'content', type: 'string'),
                new OA\Property(property: 'template', type: 'string'),
                new OA\Property(property: 'is_active', type: 'boolean'),
                new OA\Property(property: 'meta_title', type: 'string'),
                new OA\Property(property: 'meta_description', type: 'string'),
                new OA\Property(property: 'blocks', type: 'array', items: new OA\Items(
                    properties: [
                        new OA\Property(property: 'type', type: 'string'),
                        new OA\Property(property: 'content', type: 'object'),
                        new OA\Property(property: 'order_index', type: 'integer'),
                    ],
                )),
            ],
        )),
        responses: [
            new OA\Response(response: 200, description: 'Sayfa güncellendi'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function update(UpdatePageRequest $request, Page $page, UpdatePageAction $action): JsonResponse
    {
        return DB::transaction(function () use ($request, $page, $action) {
            $validated = $request->validated();
            $blocks = $validated['blocks'] ?? null;
            unset($validated['blocks']);

            $dto = PageData::fromArray(array_merge($page->toArray(), $validated));
            $page = $action->execute($page, $dto);

            if ($blocks !== null) {
                $page->blocks()->delete();
                foreach ($blocks as $index => $block) {
                    $page->blocks()->create([
                        'type' => $block['type'],
                        'content' => $block['content'],
                        'order_index' => $block['order_index'] ?? $index,
                    ]);
                }
            }

            return response()->json(new PageResource($page->load('blocks')));
        });
    }

    #[OA\Delete(
        path: '/api/admin/pages/{page}',
        summary: 'Sayfa sil',
        tags: ['Admin - Pages'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'page', in: 'path', required: true, schema: new OA\Schema(type: 'integer'))],
        responses: [new OA\Response(response: 200, description: 'Sayfa silindi')],
    )]
    public function destroy(Page $page, DeletePageAction $action): JsonResponse
    {
        $page->blocks()->delete();
        $action->execute($page);

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