<?php

namespace App\Http\Controllers\Api\Admin;

use App\Actions\User\CreateUserAction;
use App\Actions\User\DeleteUserAction;
use App\Actions\User\UpdateUserAction;
use App\DTOs\UserData;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\StoreUserRequest;
use App\Http\Requests\User\UpdateUserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use OpenApi\Attributes as OA;

class UserController extends Controller
{
    public function __construct(private UserRepositoryInterface $repository) {}

    #[OA\Get(
        path: '/api/admin/users',
        summary: 'Admin kullanıcılarını listele',
        tags: ['Admin - Users'],
        security: [['sanctum' => []]],
        parameters: [
            new OA\Parameter(name: 'search', in: 'query', required: false, schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'role', 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: 'Kullanıcı listesi')],
    )]
    public function index(Request $request): AnonymousResourceCollection
    {
        $users = $this->repository->paginate(
            filters: $request->only('search', 'role'),
            perPage: $request->integer('per_page', 15),
        );

        return UserResource::collection($users);
    }

    #[OA\Post(
        path: '/api/admin/users',
        summary: 'Yeni admin kullanıcı oluştur',
        tags: ['Admin - Users'],
        security: [['sanctum' => []]],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['name', 'email', 'password', 'password_confirmation', 'role'],
                properties: [
                    new OA\Property(property: 'name', type: 'string', example: 'Editör Kullanıcı'),
                    new OA\Property(property: 'email', type: 'string', format: 'email', example: 'editor@bogazici.com'),
                    new OA\Property(property: 'password', type: 'string', format: 'password', example: 'password123'),
                    new OA\Property(property: 'password_confirmation', type: 'string', format: 'password', example: 'password123'),
                    new OA\Property(property: 'role', type: 'string', example: 'editor'),
                ],
            ),
        ),
        responses: [
            new OA\Response(response: 201, description: 'Kullanıcı oluşturuldu'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function store(StoreUserRequest $request, CreateUserAction $action): JsonResponse
    {
        $dto = UserData::fromArray($request->validated());
        $user = $action->execute($dto);

        return (new UserResource($user))
            ->response()
            ->setStatusCode(201);
    }

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

        return new UserResource($user);
    }

    #[OA\Put(
        path: '/api/admin/users/{user}',
        summary: 'Kullanıcı güncelle',
        tags: ['Admin - Users'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'user', 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'),
                new OA\Property(property: 'email', type: 'string', format: 'email'),
                new OA\Property(property: 'password', type: 'string', format: 'password'),
                new OA\Property(property: 'password_confirmation', type: 'string', format: 'password'),
                new OA\Property(property: 'role', type: 'string', example: 'editor'),
            ],
        )),
        responses: [
            new OA\Response(response: 200, description: 'Kullanıcı güncellendi'),
            new OA\Response(response: 422, description: 'Validasyon hatası'),
        ],
    )]
    public function update(UpdateUserRequest $request, User $user, UpdateUserAction $action): UserResource
    {
        $dto = UserData::fromArray($request->validated());
        $user = $action->execute($user, $dto);

        return new UserResource($user);
    }

    #[OA\Delete(
        path: '/api/admin/users/{user}',
        summary: 'Kullanıcı sil (soft delete)',
        tags: ['Admin - Users'],
        security: [['sanctum' => []]],
        parameters: [new OA\Parameter(name: 'user', in: 'path', required: true, schema: new OA\Schema(type: 'integer'))],
        responses: [
            new OA\Response(response: 200, description: 'Kullanıcı silindi'),
            new OA\Response(response: 403, description: 'Kendini silemezsin'),
            new OA\Response(response: 404, description: 'Bulunamadı'),
        ],
    )]
    public function destroy(User $user, DeleteUserAction $action): JsonResponse
    {
        if ($user->id === auth()->id()) {
            return response()->json(['message' => 'Kendinizi silemezsiniz.'], 403);
        }

        $action->execute($user);

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