<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Resources\PageBlockResource;
use App\Models\Page;
use App\Models\PageBlock;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use OpenApi\Attributes as OA;

class BlockController extends Controller
{
    #[OA\Get(
        path: '/api/admin/pages/{page}/blocks',
        summary: 'Sayfa bloklarını listele',
        tags: ['Admin - Page Blocks'],
        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: 'Blok listesi')],
    )]
    public function index(Page $page): AnonymousResourceCollection
    {
        return PageBlockResource::collection(
            $page->blocks()->orderBy('order_index')->get()
        );
    }

    #[OA\Post(
        path: '/api/admin/pages/{page}/blocks',
        summary: 'Yeni blok oluştur',
        tags: ['Admin - Page Blocks'],
        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(
            required: ['type', 'content'],
            properties: [
                new OA\Property(property: 'type', type: 'string'),
                new OA\Property(property: 'content', type: 'object'),
                new OA\Property(property: 'order_index', type: 'integer'),
                new OA\Property(property: 'is_active', type: 'boolean'),
            ],
        )),
        responses: [
            new OA\Response(response: 201, description: 'Blok oluşturuldu'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function store(Request $request, Page $page): JsonResponse
    {
        $validated = $request->validate([
            'type' => ['required', 'string', 'max:50'],
            'content' => ['present', 'array'],
            'order_index' => ['sometimes', 'integer', 'min:0'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $validated['order_index'] ??= $page->blocks()->max('order_index') + 1;

        $block = $page->blocks()->create($validated);

        return response()->json(new PageBlockResource($block), 201);
    }

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

    #[OA\Put(
        path: '/api/admin/pages/{page}/blocks/{block}',
        summary: 'Blok güncelle',
        tags: ['Admin - Page Blocks'],
        security: [['sanctum' => []]],
        parameters: [
            new OA\Parameter(name: 'page', in: 'path', required: true, schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'block', 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: 'type', type: 'string'),
                new OA\Property(property: 'content', type: 'object'),
                new OA\Property(property: 'order_index', type: 'integer'),
                new OA\Property(property: 'is_active', type: 'boolean'),
            ],
        )),
        responses: [
            new OA\Response(response: 200, description: 'Blok güncellendi'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function update(Request $request, Page $page, PageBlock $block): JsonResponse
    {
        $validated = $request->validate([
            'type' => ['sometimes', 'string', 'max:50'],
            'content' => ['sometimes', 'array'],
            'order_index' => ['sometimes', 'integer', 'min:0'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $block->update($validated);

        return response()->json(new PageBlockResource($block->fresh()));
    }

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

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

    #[OA\Post(
        path: '/api/admin/pages/{page}/blocks/reorder',
        summary: 'Blok sıralamasını güncelle',
        tags: ['Admin - Page Blocks'],
        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(
            required: ['items'],
            properties: [
                new OA\Property(property: 'items', type: 'array', items: new OA\Items(
                    properties: [
                        new OA\Property(property: 'id', type: 'integer'),
                        new OA\Property(property: 'order_index', type: 'integer'),
                    ],
                )),
            ],
        )),
        responses: [new OA\Response(response: 200, description: 'Sıralama güncellendi')],
    )]
    public function reorder(Request $request, Page $page): JsonResponse
    {
        $validated = $request->validate([
            'items' => ['required', 'array', 'min:1'],
            'items.*.id' => ['required', 'integer', 'exists:page_blocks,id'],
            'items.*.order_index' => ['required', 'integer', 'min:0'],
        ]);

        foreach ($validated['items'] as $item) {
            $page->blocks()
                ->where('id', $item['id'])
                ->update(['order_index' => $item['order_index']]);
        }

        return response()->json(['message' => 'Blok sıralaması güncellendi.']);
    }
}
