import { Get, Body, Post, Route, Tags, SuccessResponse, Response, Security, Put, Path, Delete } from 'tsoa';
import { UserManagementService } from '../services/usermanagement.service';
import { ValidationError } from '../middleware/errorHandler';
import { ListUsersResponse, GetUserResponse, ActivateAccountResponse, DeactivateAccountResponse, UpdateRole, UpdateRoleResponse } from '../types/usersmanagement.types';
import { getUserByIdValidator, updateUserRoleValidator } from '../validators/usermanagement.validator';

@Route('api/admin/usermanagement')
@Tags('Admin/UserManagement')
export class UserManagementController {

    private userManagementService = new UserManagementService();

    @Get('users')
    @Security('jwt', ['admin'])
    @SuccessResponse('200', 'Users fetched successfully')
    @Response('401', 'Invalid or expired token')
    public async listUsers(): Promise<ListUsersResponse> {
        return await this.userManagementService.listUsers();
    }

    @Get('users/{id}')
    @Security('jwt', ['admin'])
    @SuccessResponse('200', 'User fetched successfully')
    @Response('401', 'Invalid or expired token')
    public async getUserById(@Path() id: number): Promise<GetUserResponse> {
        const { error, value } = getUserByIdValidator.validate({ id });
        if (error) throw new ValidationError(error.details[0].message);
        return await this.userManagementService.getUserById(value.id);
    }

    @Put('role/{id}')
    @Security('jwt', ['admin'])
    @SuccessResponse('200', 'User role updated successfully')
    @Response('401', 'Invalid or expired token')
    public async updateUserRole(@Body() body: UpdateRole): Promise<UpdateRoleResponse> {
        const { error, value } = updateUserRoleValidator.validate(body);
        if (error) throw new ValidationError(error.details[0].message);
        return await this.userManagementService.updateUserRole(value.id, value.role_id);
    }

    @Delete('users/{id}')
    @Security('jwt', ['admin'])
    @SuccessResponse('200', 'User deleted successfully')
    @Response('401', 'Invalid or expired token')
    public async deleteUser(@Path() id: number): Promise<DeactivateAccountResponse> {
        const { error, value } = getUserByIdValidator.validate({ id });
        if (error) throw new ValidationError(error.details[0].message);
        return await this.userManagementService.deleteUser(value.id);
    }

    @Put('users/activate/{id}')
    @Security('jwt', ['admin'])
    @SuccessResponse('200', 'User activated successfully')
    @Response('401', 'Invalid or expired token')
    public async activateUser(@Path() id: number): Promise<ActivateAccountResponse> {
        const { error, value } = getUserByIdValidator.validate({ id });
        if (error) throw new ValidationError(error.details[0].message);
        return await this.userManagementService.activateAccount(value.id);
    }

}

