import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MerchantLocation } from '../location/location.entity';
import { Repository } from 'typeorm';
import { MerchantDocumnets } from './merchantdocuments.entity';

@Injectable()
export class MerchantdocumentsService {
  constructor(
    @InjectRepository(MerchantDocumnets)
    private merchantDocumentRepo: Repository<MerchantDocumnets>,
  ) {}


  async findAll(): Promise<MerchantDocumnets[]> {
    return await this.merchantDocumentRepo.find(); // assuming `repo` is injected repository of MerchantDocumnets
  }
  

  async addMerchantDocuments(data: {
    fileName: string;
    description: string;
    merchantId: number;
  }): Promise<any> {
    console.log('merchant id : ', data.merchantId);
    const document = this.merchantDocumentRepo.create({
      Path: data.fileName,
      Description: data.description,
      Merchant_idMerchant: data.merchantId,
    });

    return await this.merchantDocumentRepo.save(document);
  }

  async findByMerchantId(merchantId: number): Promise<MerchantDocumnets[]> {
    return await this.merchantDocumentRepo.find({
      where: { Merchant_idMerchant: merchantId },
    });
  }

  async deleteById(id: number): Promise<void> {
    await this.merchantDocumentRepo.delete(id);
  }

  // Delete documents not included in the provided paths
  async deleteDocumentsNotInList(
    merchantId: number,
    existingPaths: string[],
  ): Promise<void> {
    const allDocs = await this.findByMerchantId(merchantId);

    const toDelete = allDocs.filter((doc) => !existingPaths.includes(doc.Path));

    if (toDelete.length > 0) {
      const idsToDelete = toDelete.map((doc) => doc.idMerchant_Document);
      await this.merchantDocumentRepo.delete(idsToDelete);
    }
  }

  async updateDescriptionById(id: number, description: string): Promise<any> {
    console.log('id', id);
    console.log(description);
    return await this.merchantDocumentRepo.update(id, {
      Description: description,
    });
  }
}
