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

@Injectable()
export class FranchiseHistoryService {
  constructor(
    @InjectRepository(FranchiseHistory)
    private franchiseHistoryRepository: Repository<FranchiseHistory>,
  ) {}

  async getHistory(franchiseId?: number, tempFranchiseId?: number) {
    const query = this.franchiseHistoryRepository
      .createQueryBuilder('fh')
      .orderBy('fh.createdAt', 'DESC');

    if (franchiseId) {
      query.where('fh.franchiseId = :franchiseId', { franchiseId });
    }

    if (tempFranchiseId) {
      query.where('fh.tempFranchiseId = :tempFranchiseId', { tempFranchiseId });
    }

    return await query.getMany();
  }

  async getFranchiseHistory(franchiseId: number) {
    return await this.franchiseHistoryRepository.find({
      where: { franchiseId },
      order: { createdAt: 'DESC' },
    });
  }

  async getApplicationHistory(tempFranchiseId: number) {
    return await this.franchiseHistoryRepository.find({
      where: { tempFranchiseId },
      order: { createdAt: 'DESC' },
    });
  }

  async createHistoryEntry(data: {
    franchiseId?: number;
    tempFranchiseId?: number;
    action: 'applied' | 'approved' | 'rejected' | 'updated';
    performedBy?: number;
    remarks?: string;
  }) {
    return await this.franchiseHistoryRepository.save(data);
  }
}
