import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { SMSHistory } from './sms-history.entity';
import { Repository } from 'typeorm';

@Injectable()
export class SmsHistoryService {
  constructor(
    @InjectRepository(SMSHistory)
    private smsHistoryRepo: Repository<SMSHistory>,
  ) {}
  async getAll(): Promise<any> {
    const data = await this.smsHistoryRepo.find();
    return data;
  }

  async getById(id: number): Promise<any> {
    const data = await this.smsHistoryRepo.findBy({ idSMS_History: id });
    return data;
  }

  async add(body: any): Promise<any> {
    const data = await this.smsHistoryRepo.create(body);
    await this.smsHistoryRepo.save(data);
    return {
      message: 'History adding completed!',
    };
  }

  async update(id: number, body: any): Promise<any> {
    const template = await this.smsHistoryRepo.findOneBy({ idSMS_History: id });
    if (!template) {
      throw new Error('History not found');
    }

    const updated = this.smsHistoryRepo.merge(template, body);
    await this.smsHistoryRepo.save(updated);

    return {
      message: 'History update completed!',
    };
  }

  async getHistoryByCustomerId(id: number): Promise<any> {
    const data = await this.smsHistoryRepo.findBy({ Customer_idCustomer: id });
    return data;
  }
}
