import {
  Controller,
  Get,
  Post,
  Patch,
  Param,
  Body,
  Query,
  UseGuards,
  HttpCode,
  HttpStatus,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../../../common/decorators/current-user.decorator';
import { TimelineService } from '../services/timeline.service';
import { AddCommentDto } from '../dto/add-comment.dto';

@ApiTags('CRM Timeline')
@ApiBearerAuth()
@Controller('crm/deals/:dealId/timeline')
@UseGuards(JwtAuthGuard)
export class TimelineController {
  constructor(private readonly timeline: TimelineService) {}

  @Get()
  @ApiOperation({ summary: 'Get deal timeline' })
  @ApiQuery({ name: 'cursor', required: false })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  @ApiResponse({ status: 200 })
  async getTimeline(
    @Param('dealId', ParseUUIDPipe) dealId: string,
    @Query('cursor') cursor?: string,
    @Query('limit') limit?: string,
  ) {
    return this.timeline.getByDeal(dealId, cursor, limit ? +limit : undefined);
  }

  @Post('comment')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Add comment to deal timeline' })
  @ApiResponse({ status: 201 })
  async addComment(
    @Param('dealId', ParseUUIDPipe) dealId: string,
    @CurrentUser() user: any,
    @Body() dto: AddCommentDto,
  ) {
    return this.timeline.addEntry(dealId, user.sub, 'COMMENT', {
      subject: 'Комментарий',
      content: dto.content,
    });
  }

  @Patch(':id/pin')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Pin timeline entry' })
  async pin(@Param('id', ParseUUIDPipe) id: string) {
    return this.timeline.pin(id);
  }

  @Patch(':id/unpin')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Unpin timeline entry' })
  async unpin(@Param('id', ParseUUIDPipe) id: string) {
    return this.timeline.unpin(id);
  }
}
