import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
  Request,
  Query,
} from '@nestjs/common';
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';
import { KnowledgeGroupService, CreateGroupDto, UpdateGroupDto } from './knowledge-group.service';

@Controller('knowledge-groups')
@UseGuards(CombinedAuthGuard, RolesGuard)
export class KnowledgeGroupController {
  constructor(private readonly groupService: KnowledgeGroupService) { }

  @Get()
  async findAll(
    @Request() req,
    @Query('flat') flat?: string,
    @Query('page') page?: number,
    @Query('limit') limit?: number,
    @Query('name') name?: string,
  ) {
    // All users can see all groups for their tenant
    return await this.groupService.findAll(req.user.id, req.user.tenantId, {
      flat: flat === 'true',
      page: page ? Number(page) : undefined,
      limit: limit ? Number(limit) : undefined,
      name,
    });
  }

  @Get(':id')
  async findOne(@Param('id') id: string, @Request() req) {
    return await this.groupService.findOne(id, req.user.id, req.user.tenantId);
  }

  @Post()
  @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
  async create(@Body() createGroupDto: CreateGroupDto, @Request() req) {
    return await this.groupService.create(req.user.id, req.user.tenantId, createGroupDto);
  }

  @Put(':id')
  @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
  async update(
    @Param('id') id: string,
    @Body() updateGroupDto: UpdateGroupDto,
    @Request() req,
  ) {
    return await this.groupService.update(id, req.user.id, req.user.tenantId, updateGroupDto);
  }

  @Delete(':id')
  @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
  async remove(@Param('id') id: string, @Request() req) {
    await this.groupService.remove(id, req.user.id, req.user.tenantId);
    return { message: 'Group deleted successfully' };
  }

  @Get(':id/files')
  async getGroupFiles(@Param('id') id: string, @Request() req) {
    const files = await this.groupService.getGroupFiles(id, req.user.id, req.user.tenantId);
    return { files };
  }
}