<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Role\StoreRoleRequest;
use App\Http\Requests\Role\UpdateRoleRequest;
use App\Http\Resources\RoleResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use OpenApi\Attributes as OA;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    #[OA\Get(
        path: '/api/admin/roles',
        summary: 'Rolleri listele',
        tags: ['Admin - Roles'],
        security: [['sanctum' => []]],
        responses: [new OA\Response(response: 200, description: 'Rol listesi')],
    )]
    public function index(): AnonymousResourceCollection
    {
        $roles = Role::query()
            ->with('permissions')
            ->get()
            ->loadCount('users');

        return RoleResource::collection($roles);
    }

    #[OA\Post(
        path: '/api/admin/roles',
        summary: 'Yeni rol oluştur',
        tags: ['Admin - Roles'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['name', 'permissions'],
                properties: [
                    new OA\Property(property: 'name', type: 'string', example: 'moderator'),
                    new OA\Property(property: 'permissions', type: 'array', items: new OA\Items(type: 'string'), example: ['view-category', 'view-course']),
                ],
            ),
        ),
        responses: [
            new OA\Response(response: 201, description: 'Rol oluşturuldu'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function store(StoreRoleRequest $request): JsonResponse
    {
        $role = Role::create([
            'name' => $request->validated('name'),
            'guard_name' => 'web',
        ]);

        $role->syncPermissions($request->validated('permissions'));
        $role->load('permissions');

        return (new RoleResource($role))
            ->response()
            ->setStatusCode(201);
    }

    #[OA\Get(
        path: '/api/admin/roles/{role}',
        summary: 'Rol detayı',
        tags: ['Admin - Roles'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'role', in: 'path', required: true, schema: new OA\Schema(type: 'integer'))],
        responses: [
            new OA\Response(response: 200, description: 'Rol detayı'),
            new OA\Response(response: 404, description: 'Bulunamadı'),
        ],
    )]
    public function show(Role $role): RoleResource
    {
        $role->load('permissions');
        $role->loadCount('users');

        return new RoleResource($role);
    }

    #[OA\Put(
        path: '/api/admin/roles/{role}',
        summary: 'Rol güncelle',
        tags: ['Admin - Roles'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'role', 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: 'name', type: 'string', example: 'moderator'),
                new OA\Property(property: 'permissions', type: 'array', items: new OA\Items(type: 'string')),
            ],
        )),
        responses: [
            new OA\Response(response: 200, description: 'Rol güncellendi'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function update(UpdateRoleRequest $request, Role $role): RoleResource
    {
        $validated = $request->validated();

        if (isset($validated['name'])) {
            $role->update(['name' => $validated['name']]);
        }

        if (isset($validated['permissions'])) {
            $role->syncPermissions($validated['permissions']);
        }

        $role->load('permissions');

        return new RoleResource($role);
    }

    #[OA\Delete(
        path: '/api/admin/roles/{role}',
        summary: 'Rol sil',
        tags: ['Admin - Roles'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'role', in: 'path', required: true, schema: new OA\Schema(type: 'integer'))],
        responses: [
            new OA\Response(response: 200, description: 'Rol silindi'),
            new OA\Response(response: 403, description: 'Varsayılan roller silinemez'),
            new OA\Response(response: 404, description: 'Bulunamadı'),
        ],
    )]
    public function destroy(Role $role): JsonResponse
    {
        if (in_array($role->name, ['super-admin', 'editor'])) {
            return response()->json(['message' => 'Varsayılan roller silinemez.'], 403);
        }

        if ($role->users()->count() > 0) {
            return response()->json(['message' => 'Bu role atanmış kullanıcılar var. Önce kullanıcıların rollerini değiştirin.'], 422);
        }

        $role->delete();

        return response()->json(['message' => 'Rol başarıyla silindi.']);
    }

    #[OA\Get(
        path: '/api/admin/permissions',
        summary: 'Tüm yetkileri listele',
        description: 'Rol oluştururken/düzenlerken kullanılacak tüm mevcut yetkileri modül bazlı gruplandırarak döner.',
        tags: ['Admin - Roles'],
        security: [['sanctum' => []]],
        responses: [new OA\Response(response: 200, description: 'Yetki listesi')],
    )]
    public function permissions(): JsonResponse
    {
        $permissions = Permission::query()
            ->where('guard_name', 'web')
            ->orderBy('name')
            ->pluck('name');

        // Modül bazlı gruplandırma
        $grouped = [];
        foreach ($permissions as $permission) {
            $parts = explode('-', $permission, 2);
            if (count($parts) === 2) {
                $grouped[$parts[1]][] = $permission;
            }
        }

        return response()->json([
            'data' => [
                'all' => $permissions,
                'grouped' => $grouped,
            ],
        ]);
    }
}
