import { Controller, Get, Post, Put, Body, UseGuards, Request, Query, UseInterceptors, UploadedFile, Res } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import { AdminService } from './admin.service';
import { CombinedAuthGuard } from '../auth/combined-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { Roles } from '../auth/roles.decorator';
import { UserRole } from '../user/user-role.enum';

@Controller('v1/admin')
@UseGuards(CombinedAuthGuard, RolesGuard)
export class AdminController {
    constructor(private readonly adminService: AdminService) { }

    @Get('users')
    @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
    async getUsers(
        @Request() req: any,
        @Query('page') page?: string,
        @Query('limit') limit?: string,
    ) {
        const isSuperAdmin = req.user.role === UserRole.SUPER_ADMIN;
        return this.adminService.getTenantUsers(
            isSuperAdmin ? undefined : req.user.tenantId,
            page ? parseInt(page) : undefined,
            limit ? parseInt(limit) : undefined
        );
    }

    @Get('users/export')
    @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
    async getUsersExport(@Request() req: any, @Res() res: Response) {
        const isSuperAdmin = req.user.role === UserRole.SUPER_ADMIN;
        const buffer = await this.adminService.exportUsers(isSuperAdmin ? undefined : req.user.tenantId);
        res.set({
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Disposition': 'attachment; filename="users_export.xlsx"',
            'Content-Length': buffer.length,
        });
        res.end(buffer);
    }

    @Post('users/import')
    @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
    @UseInterceptors(FileInterceptor('file'))
    async importUsers(@Request() req: any, @UploadedFile() file: any) {
        const isSuperAdmin = req.user.role === UserRole.SUPER_ADMIN;
        return this.adminService.importUsers(isSuperAdmin ? undefined : req.user.tenantId, file);
    }

    @Get('settings')
    async getSettings(@Request() req: any) {
        return this.adminService.getTenantSettings(req.user.tenantId);
    }

    @Put('settings')
    @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
    async updateSettings(@Request() req: any, @Body() body: any) {
        return this.adminService.updateTenantSettings(req.user.tenantId, body);
    }

    @Get('pending-shares')
    @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
    async getPendingShares(@Request() req: any) {
        return this.adminService.getPendingShares(req.user.tenantId);
    }
}
