import {
    Body,
    Controller,
    Delete,
    ForbiddenException,
    Get,
    Param,
    Patch,
    Post,
    Put,
    Request,
    UseGuards,
    HttpCode,
    Query,
} from '@nestjs/common';
import { TenantService } from './tenant.service';
import { CombinedAuthGuard } from '../auth/combined-auth.guard';
import { SuperAdminGuard } from '../auth/super-admin.guard';

@Controller('tenants')
@UseGuards(CombinedAuthGuard, SuperAdminGuard)
export class TenantController {
    constructor(private readonly tenantService: TenantService) { }

    @Get()
    findAll(
        @Query('page') page?: string,
        @Query('limit') limit?: string,
    ) {
        const p = page ? parseInt(page) : undefined;
        const l = limit ? parseInt(limit) : undefined;
        return this.tenantService.findAll(p, l);
    }

    @Get(':id')
    findOne(@Param('id') id: string) {
        return this.tenantService.findById(id);
    }

    @Post()
    create(@Body() body: { name: string; domain?: string; parentId?: string }) {
        return this.tenantService.create(body.name, body.domain, body.parentId);
    }

    @Put(':id')
    update(@Param('id') id: string, @Body() body: { name?: string; domain?: string; parentId?: string; isActive?: boolean }) {
        return this.tenantService.update(id, body);
    }

    @Delete(':id')
    remove(@Param('id') id: string) {
        return this.tenantService.remove(id);
    }

    @Get(':id/settings')
    getSettings(@Param('id') id: string) {
        return this.tenantService.getSettings(id);
    }

    @Put(':id/settings')
    updateSettings(@Param('id') id: string, @Body() body: any) {
        return this.tenantService.updateSettings(id, body);
    }

    @Get(':id/members')
    getMembers(
        @Param('id') id: string,
        @Query('page') page?: string,
        @Query('limit') limit?: string,
    ) {
        const p = page ? parseInt(page) : undefined;
        const l = limit ? parseInt(limit) : undefined;
        return this.tenantService.getMembers(id, p, l);
    }

    @Post(':id/members')
    addMember(
        @Param('id') id: string,
        @Body() body: { userId: string; role?: string },
    ) {
        return this.tenantService.addMember(id, body.userId, body.role);
    }

    @Patch(':id/members/:userId')
    async updateMemberRole(
        @Param('id') id: string,
        @Param('userId') userId: string,
        @Body() body: { role: string },
    ) {
        return this.tenantService.updateMemberRole(id, userId, body.role);
    }

    @Delete(':id/members/:userId')
    @HttpCode(204)
    async removeMember(
        @Param('id') id: string,
        @Param('userId') userId: string,
    ) {
        await this.tenantService.removeMember(id, userId);
    }

    @Get(':id/members/ids')
    getMemberIds(
        @Param('id') id: string,
    ) {
        return this.tenantService.getMemberIds(id);
    }
}
