import { applyDecorators } from '@nestjs/common';
import {
    ApiOperation,
    ApiBody,
    ApiResponse,
    ApiBearerAuth,
    ApiBadRequestResponse,
    ApiConflictResponse,
    ApiUnauthorizedResponse,
    ApiNotFoundResponse,
} from '@nestjs/swagger';
import {
    RegisterDto,
    LoginDto,
    RequestOtpDto,
    VerifyOtpDto,
} from './dtos';
import { SessionSchemaType, SuccessSchemaType, UserSchemaType } from './types/auth.swagger.types';


const successSchema = (dataSchema: object): SuccessSchemaType => ({
    type: 'object',
    properties: {
        statusCode: { type: 'number', example: 200 },
        success: { type: 'boolean', example: true },
        message: { type: 'string' },
        data: dataSchema,
    },
});

const userData: UserSchemaType = {
    type: 'object',
    properties: {
        id: { type: 'string' },
        username: { type: 'string' },
        email: { type: 'string' },
    },
};

const sessionData: SessionSchemaType = {
    type: 'object',
    properties: {
        id: { type: 'string' },
        username: { type: 'string' },
        email: { type: 'string' },
        isActive: { type: 'boolean' },
        accessToken: { type: 'string' },
        refreshToken: { type: 'string' },
    },
};

export function ApiAuthBearer(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiBearerAuth(),
        ApiUnauthorizedResponse({ description: 'Unauthorized - invalid or missing token' }),
    );
}

export function ApiRegister(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiOperation({
            summary: 'Register a new user',
            description: 'Create a new user account with email, username, and password',
        }),
        ApiBody({ type: RegisterDto }),
        ApiResponse({
            status: 201,
            description: 'User registered successfully',
            schema: successSchema({
                type: 'object',
                properties: {
                    ...userData.properties,
                    message: { type: 'string' },
                },
            }),
        }),
        ApiBadRequestResponse({ description: 'Bad request - validation error' }),
        ApiConflictResponse({ description: 'Conflict - user already exists' }),
    );
}

export function ApiRequestOtp(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiOperation({
            summary: 'Request OTP for authentication',
            description: 'Send OTP code to user email for login or registration',
        }),
        ApiBody({ type: RequestOtpDto }),
        ApiResponse({
            status: 200,
            description: 'OTP sent successfully',
            schema: successSchema({
                type: 'object',
                properties: {
                    message: { type: 'string' },
                    email: { type: 'string' },
                    expiresIn: { type: 'number' },
                },
            }),
        }),
        ApiBadRequestResponse({ description: 'Bad request - invalid email' }),
        ApiNotFoundResponse({ description: 'Not found - user not found' }),
    );
}

export function ApiVerifyOtp(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiOperation({
            summary: 'Verify OTP and complete login',
            description: 'Verify OTP code and authenticate user',
        }),
        ApiBody({ type: VerifyOtpDto }),
        ApiResponse({
            status: 200,
            description: 'Login successful',
            schema: successSchema(sessionData),
        }),
        ApiBadRequestResponse({ description: 'Bad request - invalid OTP' }),
        ApiUnauthorizedResponse({ description: 'Unauthorized - invalid or expired OTP' }),
    );
}

export function ApiLogin(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiOperation({
            summary: 'Login with credentials',
            description: 'Authenticate user with username/email and password',
        }),
        ApiBody({ type: LoginDto }),
        ApiResponse({
            status: 200,
            description: 'Login successful',
            schema: successSchema(sessionData),
        }),
        ApiBadRequestResponse({ description: 'Bad request - invalid credentials' }),
        ApiUnauthorizedResponse({ description: 'Unauthorized - invalid username/email or password' }),
    );
}

export function ApiLogout(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiOperation({
            summary: 'Logout user',
            description: 'Logout from current device session',
        }),
        ApiResponse({
            status: 200,
            description: 'Logout successful',
            schema: successSchema({ type: 'null' }),
        }),
    );
}

export function ApiLogoutAll(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiOperation({
            summary: 'Logout from all devices',
            description: 'Invalidate all active sessions for the user',
        }),
        ApiResponse({
            status: 200,
            description: 'Logged out from all devices',
            schema: successSchema({ type: 'null' }),
        }),
    );
}

export function ApiGetCurrentUser(): <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void {
    return applyDecorators(
        ApiOperation({
            summary: 'Get current user info',
            description: 'Retrieve information about the currently authenticated user',
        }),
        ApiResponse({
            status: 200,
            description: 'User info retrieved',
            schema: successSchema({
                type: 'object',
                properties: {
                    ...userData.properties,
                    roles: { type: 'string[]' },
                },
            }),
        }),
    );
}
