import { Body, Controller, Get, Headers, Param, Patch, Post, Query } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { firstValueFrom } from 'rxjs';
import { map } from 'rxjs/operators';
import { CoreGrpcService } from '../core-grpc.service';
import { getAuthorizedUserId } from '../document-access';
import {
  CreateChatRoomDto,
  SendChatMessageDto,
  SetRoomNotificationsMutedDto,
  UpdateChatRoomDto,
  VotePollDto
} from '../dto/chat.dto';

@ApiTags('Чат')
@ApiBearerAuth()
@Controller('chat')
export class ChatController {
  constructor(
    private readonly core: CoreGrpcService,
    private readonly jwt: JwtService
  ) {}

  private async auth(authorization?: string) {
    return getAuthorizedUserId(this.jwt, this.core, authorization);
  }

  @Get('groups/:groupId/rooms')
  @ApiOperation({ summary: 'Список чатов семьи' })
  async listRooms(@Headers('authorization') authorization: string | undefined, @Param('groupId') groupId: string) {
    const userId = await this.auth(authorization);
    return firstValueFrom(
      this.core.chat.ListRooms({ userId, groupId }).pipe(
        map((response) => {
          const payload = response as { rooms?: unknown[] };
          return { rooms: payload.rooms ?? [] };
        })
      )
    );
  }

  @Post('groups/:groupId/rooms')
  @ApiOperation({ summary: 'Создать групповой чат' })
  async createRoom(
    @Headers('authorization') authorization: string | undefined,
    @Param('groupId') groupId: string,
    @Body() dto: CreateChatRoomDto
  ) {
    const userId = await this.auth(authorization);
    return firstValueFrom(
      this.core.chat.CreateRoom({ userId, groupId, name: dto.name, memberUserIds: dto.memberUserIds ?? [] })
    );
  }

  @Patch('rooms/:roomId')
  @ApiOperation({ summary: 'Настройки чата' })
  async updateRoom(
    @Headers('authorization') authorization: string | undefined,
    @Param('roomId') roomId: string,
    @Body() dto: UpdateChatRoomDto
  ) {
    const userId = await this.auth(authorization);
    return firstValueFrom(
      this.core.chat.UpdateRoomSettings({
        userId,
        roomId,
        name: dto.name,
        notificationsMuted: dto.notificationsMuted
      })
    );
  }

  @Get('rooms/:roomId/messages')
  @ApiOperation({ summary: 'Сообщения чата' })
  async listMessages(
    @Headers('authorization') authorization: string | undefined,
    @Param('roomId') roomId: string,
    @Query('beforeMessageId') beforeMessageId?: string,
    @Query('limit') limit?: string
  ) {
    const userId = await this.auth(authorization);
    return firstValueFrom(
      this.core.chat.ListMessages({
        userId,
        roomId,
        beforeMessageId,
        limit: limit ? Number(limit) : 50
      }).pipe(
        map((response) => {
          const payload = response as { messages?: unknown[] };
          return { messages: payload.messages ?? [] };
        })
      )
    );
  }

  @Post('rooms/:roomId/messages')
  @ApiOperation({ summary: 'Отправить сообщение' })
  async sendMessage(
    @Headers('authorization') authorization: string | undefined,
    @Param('roomId') roomId: string,
    @Body() dto: SendChatMessageDto
  ) {
    const userId = await this.auth(authorization);
    return firstValueFrom(
      this.core.chat.SendMessage({
        userId,
        roomId,
        type: dto.type,
        content: dto.content,
        replyToId: dto.replyToId,
        storageKey: dto.storageKey,
        mimeType: dto.mimeType,
        metadataJson: dto.metadataJson,
        poll: dto.poll
      })
    );
  }

  @Post('messages/:messageId/vote')
  @ApiOperation({ summary: 'Голос в опросе' })
  async votePoll(
    @Headers('authorization') authorization: string | undefined,
    @Param('messageId') messageId: string,
    @Body() dto: VotePollDto
  ) {
    const userId = await this.auth(authorization);
    return firstValueFrom(this.core.chat.VotePoll({ userId, messageId, optionIds: dto.optionIds }));
  }

  @Post('rooms/:roomId/mute')
  @ApiOperation({ summary: 'Выключить/включить уведомления чата' })
  async setMuted(
    @Headers('authorization') authorization: string | undefined,
    @Param('roomId') roomId: string,
    @Body() dto: SetRoomNotificationsMutedDto
  ) {
    const userId = await this.auth(authorization);
    return firstValueFrom(this.core.chat.SetRoomNotificationsMuted({ userId, roomId, muted: dto.muted }));
  }
}
