// note/note.service.ts
import { Injectable, NotFoundException } from '@nestjs/common'
import { PrismaService } from 'src/prisma/prisma.service'
import { NoteEntityType, NoteType, User } from 'generated/prisma/client'
import { CreateNoteDto } from './dto/create-note.dto'
import { BootstrapTableRequestDto } from 'src/commons/dto/bootstrap-table-request.dto'
import { BootstrapTableResponseDto } from 'src/commons/dto/bootstrap-table-response.dto'

@Injectable()
export class NotesService {
    async createNote(
        entityType: NoteEntityType,
        entityId: string,
        type: NoteType,
        content: string,
        createdBy: string,
    ) {
        return this.prisma.note.create({
            data: { entityType, entityId, type, content, createdBy },
        })
    }
    constructor(private readonly prisma: PrismaService) { }

    async create(dto: CreateNoteDto, user: User) {
        await this.assertEntityExists(dto.entityId);

        return this.prisma.note.create({
            data: {
                entityType: 'TRANSACTION', // hardcoded for now
                entityId: dto.entityId,
                type: dto.type,
                content: dto.content,
                createdBy: user.id,
            },
        });
    }

    async findByEntity(entityId: string) {
        return this.prisma.note.findMany({
            where: { entityType: 'TRANSACTION', entityId },
            orderBy: { createdAt: 'desc' },
        });
    }

    private async assertEntityExists(entityId: string) {
        const exists = await this.prisma.transaction.findUnique({
            where: { id: entityId },
            select: { id: true },
        });

        if (!exists) throw new NotFoundException(`Transaction ${entityId} not found`);
    }
}