import { Controller, Get, Post, Put, Body, UseGuards, Param, Delete, HttpCode } from '@nestjs/common';
import { SuperAdminService } from './super-admin.service';
import { TenantService } from '../tenant/tenant.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/tenants')
@UseGuards(CombinedAuthGuard, RolesGuard)
@Roles(UserRole.SUPER_ADMIN)
export class SuperAdminController {
    constructor(
        private readonly superAdminService: SuperAdminService,
        private readonly tenantService: TenantService,
    ) { }

    @Get()
    async getTenants() {
        return this.superAdminService.getAllTenants();
    }

    @Post()
    async createTenant(@Body() body: { name: string; domain?: string; adminUserId?: string }) {
        return this.superAdminService.createTenant(body.name, body.domain, body.adminUserId);
    }

    @Put(':tenantId/admin')
    async bindTenantAdmin(
        @Param('tenantId') tenantId: string,
        @Body() body: { userId: string }
    ) {
        return this.superAdminService.assignUserToTenant(body.userId, tenantId);
    }

    @Post(':tenantId/admin/new')
    async createTenantAdmin(
        @Param('tenantId') tenantId: string,
        @Body() body: { username: string; password?: string }
    ) {
        return this.superAdminService.createTenantAdmin(tenantId, body.username, body.password);
    }

    @Put(':tenantId')
    async updateTenant(
        @Param('tenantId') tenantId: string,
        @Body() body: { name?: string; domain?: string }
    ) {
        return this.superAdminService.updateTenant(tenantId, body);
    }

    @Delete(':tenantId')
    async deleteTenant(@Param('tenantId') tenantId: string) {
        return this.superAdminService.deleteTenant(tenantId);
    }

    // --- Member Management ---

    @Get(':tenantId/members')
    async getMembers(@Param('tenantId') tenantId: string) {
        return this.tenantService.getMembers(tenantId);
    }

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

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