import { Controller, Get, Post, Patch, Delete, Body, Param, Query, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { KnowledgeItemsService } from './knowledge-items.service';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import type { UserPayload } from '../../common/types';

@ApiTags('knowledge-items')
@Controller('knowledge-items')
export class KnowledgeItemsController {
  constructor(private readonly service: KnowledgeItemsService) {}

  @Post()
  @ApiOperation({ summary: '创建知识点' })
  async create(@CurrentUser() user: UserPayload, @Body() body: any) {
    return this.service.create(String(user?.id || 'anonymous'), body.knowledgeBaseId, body);
  }

  @Get(':id')
  @ApiOperation({ summary: '获取知识点详情' })
  async findOne(@Param('id') id: string) {
    return this.service.findById(id);
  }

  @Get()
  @ApiOperation({ summary: '获取知识库下的知识点列表' })
  async findByKnowledgeBase(
    @Query('knowledgeBaseId') knowledgeBaseId: string,
    @Query('sortBy') sortBy?: string,
    @Query('order') order?: string,
  ) {
    return this.service.findByKnowledgeBaseId(knowledgeBaseId, { sortBy, order });
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新知识点' })
  async update(@Param('id') id: string, @Body() body: any) {
    return this.service.update(id, body);
  }

  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '软删除知识点' })
  async delete(@CurrentUser() user: UserPayload, @Param('id') id: string) {
    await this.service.softDelete(id, String(user?.id || 'anonymous'));
    return { success: true, message: '已删除' };
  }

  @Post('batch-delete')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '批量软删除知识点' })
  async batchDelete(@CurrentUser() user: UserPayload, @Body() body: { ids: string[] }) {
    const count = await this.service.batchSoftDelete(body.ids || [], String(user?.id || 'anonymous'));
    return { success: true, message: `已删除 ${count} 个知识点`, count };
  }
}
