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';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';

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

  @Get()
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '获取知识分组列表', description: '返回当前租户的所有知识分组（树形结构）' })
  @ApiResponse({ status: 200, description: '返回分组列表' })
  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')
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '获取单个知识分组' })
  @ApiResponse({ status: 200, description: '返回分组详情' })
  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)
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '创建知识分组' })
  @ApiResponse({ status: 201, description: '创建成功' })
  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)
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '更新知识分组' })
  @ApiResponse({ status: 200, description: '更新成功' })
  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)
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '删除知识分组' })
  @ApiResponse({ status: 200, description: '删除成功' })
  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')
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '获取分组内的文件' })
  @ApiResponse({ status: 200, description: '返回文件列表' })
  async getGroupFiles(@Param('id') id: string, @Request() req) {
    const files = await this.groupService.getGroupFiles(id, req.user.id, req.user.tenantId);
    return { files };
  }
}