import {
  BadRequestException,
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Post,
  Put,
  Query,
} from '@nestjs/common';
import { NotesService } from './notes.service';
import { CreateNoteDto, UpdateNoteDto } from './dto/note.dto';

@Controller('api/v1/notes')
export class NotesController {
  constructor(private readonly service: NotesService) {}

  @Post()
  async create(@Body() dto: CreateNoteDto) {
    const data = await this.service.create(dto);
    return { success: true, message: 'Note saved', data };
  }

  @Get()
  async find(
    @Query('sessionId') sessionId: string,
    @Query('entityType') entityType?: string,
    @Query('entityId') entityId?: string,
  ) {
    if (!sessionId) throw new BadRequestException('sessionId is required');
    const data = await this.service.findBySession(
      sessionId,
      entityType,
      entityId ? Number(entityId) : undefined,
    );
    return { success: true, message: 'Success', data };
  }

  @Put(':id')
  async update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateNoteDto) {
    const data = await this.service.update(id, dto);
    return { success: true, message: 'Note updated', data };
  }

  @Delete(':id')
  async delete(@Param('id', ParseIntPipe) id: number, @Query('sessionId') sessionId: string) {
    if (!sessionId) throw new BadRequestException('sessionId is required');
    const success = await this.service.delete(id, sessionId);
    return { success, message: success ? 'Note deleted' : 'Note not found' };
  }
}
