import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Messages } from './entities/messages.entity';

@Injectable()
export class MessagesService {
  constructor(
    @InjectRepository(Messages)
    private messagesRepository: Repository<Messages>,
  ) {}

  async create(data: any): Promise<Messages> {
    const message = this.messagesRepository.create(data);
    const result = await this.messagesRepository.save(message);
    return Array.isArray(result) ? result[0] : result;
  }

  async findAll(): Promise<Messages[]> {
    return await this.messagesRepository.find();
  }

  async findOne(id: number): Promise<Messages | null> {
    return await this.messagesRepository.findOne({ where: { id } });
  }

  async findBySenderId(senderId: number): Promise<Messages[]> {
    return await this.messagesRepository.find({
      where: { sender_id: senderId },
    });
  }

  async findByRecipientId(recipientId: number): Promise<Messages[]> {
    return await this.messagesRepository.find({
      where: { recipient_id: recipientId },
    });
  }

  async update(id: number, updateMessageDto: any): Promise<Messages | null> {
    await this.messagesRepository.update(id, updateMessageDto);
    return await this.findOne(id);
  }

  async remove(id: number): Promise<void> {
    await this.messagesRepository.delete(id);
  }
}
