import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
  Request,
} 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';
import { I18nService } from '../i18n/i18n.service';

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

  @Get()
  async findAll(@Request() req) {
    // All users can see all groups for their tenant (returns tree structure)
    return await this.groupService.findAll(req.user.id, req.user.tenantId);
  }

  @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: this.i18nService.getMessage('groupDeleted') };
  }

  @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 };
  }
}