import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Answer } from './entity/answer.entity'; import { CreateAnswerDto } from './dto/create-answer.dto'; import { UpdateAnswerDto } from './dto/update-answer.dto'; @Injectable() export class AnswerService { constructor( @InjectRepository(Answer) private readonly answerRepository: Repository, ) {} async create(data: CreateAnswerDto): Promise { try { const answer = this.answerRepository.create({ ...data, metadata: data.metadata || { entries: [] }, status: data.status || 'active', }); return await this.answerRepository.save(answer); } catch (error) { throw new Error(`Failed to create answer: ${error.message}`); } } async findAll( page = 1, limit = 10, ): Promise<{ docs: Answer[]; totalDocs: number; limit: number; page: number; totalPages: number; hasNextPage: boolean; hasPrevPage: boolean; nextPage: number | null; prevPage: number | null; }> { try { const skip = (page - 1) * limit; const [docs, totalDocs] = await this.answerRepository.findAndCount({ skip, take: limit, }); const totalPages = Math.ceil(totalDocs / limit); return { docs, totalDocs, limit, page, totalPages, hasNextPage: page < totalPages, hasPrevPage: page > 1, nextPage: page < totalPages ? page + 1 : null, prevPage: page > 1 ? page - 1 : null, }; } catch (error) { throw new Error(`Failed to fetch answers: ${error.message}`); } } async findById(id: string): Promise { try { const answer = await this.answerRepository.findOne({ where: { id } }); if (!answer) { throw new NotFoundException(`Answer with ID "${id}" not found`); } return answer; } catch (error) { throw new Error(`Failed to find answer: ${error.message}`); } } async update(id: string, data: UpdateAnswerDto): Promise { try { await this.answerRepository.update({ id }, { ...data, updatedAt: new Date() }); const updatedAnswer = await this.answerRepository.findOne({ where: { id } }); if (!updatedAnswer) { throw new NotFoundException(`Answer with ID "${id}" not found`); } return updatedAnswer; } catch (error) { throw new Error(`Failed to update answer: ${error.message}`); } } async remove(id: string): Promise { try { const result = await this.answerRepository.delete({ id }); if (result.affected === 0) { throw new NotFoundException(`Answer with ID "${id}" not found`); } } catch (error) { throw new Error(`Failed to delete answer: ${error.message}`); } } }