<?php

declare(strict_types=1);

namespace App\Application\Api\V2;

use App\Framework\Attributes\ApiVersionAttribute;
use App\Framework\Attributes\Route;
use App\Framework\DateTime\Clock;
use App\Framework\Http\Headers;
use App\Framework\Http\HttpResponse;
use App\Framework\Http\Method;
use App\Framework\Http\Request;
use App\Framework\Http\Status;
use App\Framework\Serializer\Json\JsonSerializer;
use App\Framework\Serializer\Json\JsonSerializerConfig;

/**
 * Users API Controller - Version 2.0
 */
#[ApiVersionAttribute('2.0.0', introducedIn: '2.0.0')]
final readonly class UsersController
{
    public function __construct(
        private JsonSerializer $jsonSerializer,
        private Clock $clock
    ) {
    }

    #[Route(path: '/api/v2/users', method: Method::GET)]
    public function index(Request $request): HttpResponse
    {
        // V2 includes additional metadata and pagination
        $users = [
            [
                'id' => 1,
                'name' => 'John Doe',
                'email' => 'john@example.com',
                'profile' => [
                    'bio' => 'Software Developer',
                    'avatar_url' => 'https://example.com/avatars/1.jpg',
                    'verified' => true,
                ],
                'created_at' => '2024-01-01T00:00:00Z',
                'updated_at' => '2024-01-15T10:30:00Z',
            ],
            [
                'id' => 2,
                'name' => 'Jane Smith',
                'email' => 'jane@example.com',
                'profile' => [
                    'bio' => 'Product Manager',
                    'avatar_url' => 'https://example.com/avatars/2.jpg',
                    'verified' => false,
                ],
                'created_at' => '2024-01-02T00:00:00Z',
                'updated_at' => '2024-01-16T11:45:00Z',
            ],
        ];

        $response = [
            'data' => $users,
            'pagination' => [
                'page' => 1,
                'per_page' => 10,
                'total' => 2,
                'total_pages' => 1,
            ],
            'meta' => [
                'api_version' => '2.0.0',
                'response_time_ms' => random_int(50, 200),
            ],
        ];

        return new HttpResponse(
            status: Status::OK,
            headers: new Headers(['Content-Type' => 'application/json']),
            body: $this->jsonSerializer->serializeWithConfig($response, JsonSerializerConfig::pretty())
        );
    }

    #[Route(path: '/api/v2/users/{id}', method: Method::GET)]
    public function show(Request $request): HttpResponse
    {
        $userId = (int) ($request->queryParams['id'] ?? 1);

        // V2 has richer user data structure
        $user = [
            'id' => $userId,
            'name' => "User {$userId}",
            'email' => "user{$userId}@example.com",
            'profile' => [
                'bio' => "This is the bio for user {$userId}",
                'avatar_url' => "https://example.com/avatars/{$userId}.jpg",
                'website' => "https://user{$userId}.example.com",
                'location' => 'San Francisco, CA',
                'verified' => $userId % 2 === 0,
            ],
            'settings' => [
                'notifications' => true,
                'privacy_level' => 'public',
                'theme' => 'dark',
            ],
            'created_at' => '2024-01-01T00:00:00Z',
            'updated_at' => '2024-01-15T10:30:00Z',
        ];

        $response = [
            'data' => $user,
            'meta' => [
                'api_version' => '2.0.0',
                'response_time_ms' => random_int(30, 150),
            ],
        ];

        return new HttpResponse(
            status: Status::OK,
            headers: new Headers(['Content-Type' => 'application/json']),
            body: $this->jsonSerializer->serializeWithConfig($response, JsonSerializerConfig::pretty())
        );
    }

    #[Route(path: '/api/v2/users', method: Method::POST)]
    public function create(Request $request): HttpResponse
    {
        $data = $this->jsonSerializer->deserialize($request->body);

        if (! is_array($data) || empty($data['name']) || empty($data['email'])) {
            return new HttpResponse(
                status: Status::BAD_REQUEST,
                headers: new Headers(['Content-Type' => 'application/json']),
                body: $this->jsonSerializer->serialize([
                    'error' => 'Validation failed',
                    'details' => [
                        'name' => 'Name is required',
                        'email' => 'Email is required',
                    ],
                    'meta' => [
                        'api_version' => '2.0.0',
                    ],
                ])
            );
        }

        // V2 creates users with richer default data
        $user = [
            'id' => random_int(1000, 9999),
            'name' => $data['name'],
            'email' => $data['email'],
            'profile' => [
                'bio' => $data['bio'] ?? null,
                'avatar_url' => null,
                'website' => $data['website'] ?? null,
                'location' => $data['location'] ?? null,
                'verified' => false,
            ],
            'settings' => [
                'notifications' => true,
                'privacy_level' => 'public',
                'theme' => 'light',
            ],
            'created_at' => $this->clock->now()->format('Y-m-d\TH:i:s\Z'),
            'updated_at' => $this->clock->now()->format('Y-m-d\TH:i:s\Z'),
        ];

        $response = [
            'data' => $user,
            'meta' => [
                'api_version' => '2.0.0',
                'response_time_ms' => random_int(80, 250),
            ],
        ];

        return new HttpResponse(
            status: Status::CREATED,
            headers: new Headers(['Content-Type' => 'application/json']),
            body: $this->jsonSerializer->serializeWithConfig($response, JsonSerializerConfig::pretty())
        );
    }

    /**
     * New endpoint in V2 - replaces the deprecated profile endpoint
     */
    #[Route(path: '/api/v2/users/{id}/profile', method: Method::GET)]
    #[ApiVersionAttribute('2.0.0', introducedIn: '2.0.0')]
    public function getProfile(Request $request): HttpResponse
    {
        $userId = (int) ($request->queryParams['id'] ?? 1);

        // New profile format in V2
        $profile = [
            'id' => $userId,
            'bio' => "This is the comprehensive bio for user {$userId}",
            'avatar_url' => "https://example.com/avatars/{$userId}.jpg",
            'website' => "https://user{$userId}.example.com",
            'location' => 'San Francisco, CA',
            'social_links' => [
                'twitter' => "@user{$userId}",
                'github' => "github.com/user{$userId}",
                'linkedin' => "linkedin.com/in/user{$userId}",
            ],
            'stats' => [
                'followers' => random_int(100, 10000),
                'following' => random_int(50, 1000),
                'posts' => random_int(10, 500),
            ],
            'verified' => $userId % 2 === 0,
            'badges' => ['early_adopter', 'contributor'],
            'updated_at' => '2024-01-15T10:30:00Z',
        ];

        $response = [
            'data' => $profile,
            'meta' => [
                'api_version' => '2.0.0',
                'response_time_ms' => random_int(40, 180),
            ],
        ];

        return new HttpResponse(
            status: Status::OK,
            headers: new Headers(['Content-Type' => 'application/json']),
            body: $this->jsonSerializer->serializeWithConfig($response, JsonSerializerConfig::pretty())
        );
    }
}
