import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Note } from './note.entity';
import { CreateNoteDto, UpdateNoteDto } from './dto/note.dto';

@Injectable()
export class NotesService {
  constructor(
    @InjectRepository(Note)
    private readonly repo: Repository<Note>,
  ) {}

  create(dto: CreateNoteDto): Promise<Note> {
    return this.repo.save(this.repo.create(dto));
  }

  async update(id: number, dto: UpdateNoteDto): Promise<Note> {
    const note = await this.repo.findOne({ where: { id } });
    if (!note) throw new NotFoundException('Note not found');
    if (note.anonymousSessionId !== dto.anonymousSessionId) {
      throw new ForbiddenException('This note belongs to a different session');
    }
    note.content = dto.content;
    return this.repo.save(note);
  }

  findBySession(sessionId: string, entityType?: string, entityId?: number): Promise<Note[]> {
    return this.repo.find({
      where: {
        anonymousSessionId: sessionId,
        ...(entityType ? { entityType } : {}),
        ...(entityId ? { entityId } : {}),
      },
      order: { updatedAt: 'DESC' },
    });
  }

  async delete(id: number, sessionId: string): Promise<boolean> {
    const note = await this.repo.findOne({ where: { id } });
    if (!note) return false;
    if (note.anonymousSessionId !== sessionId) {
      throw new ForbiddenException('This note belongs to a different session');
    }
    const result = await this.repo.delete(id);
    return (result.affected || 0) > 0;
  }
}
