<?php

declare(strict_types=1);

namespace App\Application\GraphQL\Resolvers;

use App\Application\GraphQL\Types\UserType;
use App\Application\User\UserService;
use App\Framework\GraphQL\Attributes\GraphQLArg;
use App\Framework\GraphQL\Attributes\GraphQLField;
use App\Framework\GraphQL\Attributes\GraphQLQuery;

/**
 * GraphQL Query Resolvers for Users
 *
 * All query signatures auto-generate GraphQL schema
 */
#[GraphQLQuery(description: 'User-related queries')]
final readonly class UserQueries
{
    public function __construct(
        private UserService $userService
    ) {
    }

    /**
     * Get single user by ID
     *
     * GraphQL: user(id: Int!): User
     */
    #[GraphQLField(description: 'Fetch a user by ID')]
    public function user(int $id): ?UserType
    {
        $user = $this->userService->findById($id);

        if ($user === null) {
            return null;
        }

        return new UserType(
            id: $user->id,
            name: $user->name,
            email: $user->email,
            active: $user->active,
            createdAt: $user->createdAt?->getTimestamp()
        );
    }

    /**
     * Get list of users with optional filters
     *
     * GraphQL: users(limit: Int = 10, offset: Int = 0, active: Boolean): [User]!
     */
    #[GraphQLField(description: 'Fetch all users with pagination')]
    public function users(
        #[GraphQLArg(description: 'Maximum number of users to return')]
        int $limit = 10,
        #[GraphQLArg(description: 'Number of users to skip')]
        int $offset = 0,
        #[GraphQLArg(description: 'Filter by active status')]
        ?bool $active = null
    ): array {
        $users = $this->userService->findAll();

        // Apply filters
        if ($active !== null) {
            $users = array_filter($users, fn ($user) => $user->active === $active);
        }

        // Apply pagination
        $users = array_slice($users, $offset, $limit);

        // Convert to UserType
        return array_map(
            fn ($user) => new UserType(
                id: $user->id,
                name: $user->name,
                email: $user->email,
                active: $user->active,
                createdAt: $user->createdAt?->getTimestamp()
            ),
            $users
        );
    }
}
