import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, ILike } from 'typeorm';
import { IsoCertificate } from './entities/iso-certificate.entity';
import { CreateIsoCertificateDto } from './dto/create-iso-certificate.dto';
import { UpdateIsoCertificateDto } from './dto/update-iso-certificate.dto';
// import * as fs from 'fs';
import * as fs from 'fs';
import * as path from 'path';


@Injectable()
export class IsoCertificatesService {
  constructor(
    @InjectRepository(IsoCertificate, 'certification_db')
    private readonly isoCertificateRepository: Repository<IsoCertificate>,
  ) {}

  async create(createDto: CreateIsoCertificateDto) {
    const exists = await this.isoCertificateRepository.findOne({
      where: {
        year: createDto.year,
        month: createDto.month,
        country: createDto.country,
        companyName: createDto.companyName,
        standard: createDto.standard,
      },
    });

    if (exists) throw new ConflictException('Certificate for this company and standard already exists');

    const certificate = this.isoCertificateRepository.create(createDto);
    return this.isoCertificateRepository.save(certificate);
  }

  // Existing pagination/search
  async findAll(
    page = 1,
    filters?: {
      companyName?: string;
      standard?: string;
      year?: number;
      month?: string;
      country?: string;
    },
  ) {
    const take = 10;
    const skip = (page - 1) * take;

    const where: any = {};
    if (filters?.companyName) where.companyName = ILike(`%${filters.companyName}%`);
    if (filters?.standard) where.standard = ILike(`%${filters.standard}%`);
    if (filters?.year) where.year = filters.year;
    if (filters?.month) where.month = filters.month;
    if (filters?.country) where.country = filters.country;

    const [data, total] = await this.isoCertificateRepository.findAndCount({
      where,
     order: { id: 'DESC' },
      take,
      skip,
    });

    return {
      data,
      total,
      page,
      lastPage: Math.ceil(total / take),
    };
  }

  async findOne(id: number) {
    const certificate = await this.isoCertificateRepository.findOneBy({ id });
    if (!certificate) throw new NotFoundException(`Certificate with id ${id} not found`);
    return certificate;
  }

  async update(id: number, updateDto: UpdateIsoCertificateDto) {
    const certificate = await this.isoCertificateRepository.findOneBy({ id });
    if (!certificate) throw new NotFoundException(`Certificate with id ${id} not found`);

    // Check for duplicate
    if (updateDto.companyName || updateDto.standard || updateDto.year || updateDto.month || updateDto.country) {
      const duplicate = await this.isoCertificateRepository.findOne({
        where: {
          year: updateDto.year ?? certificate.year,
          month: updateDto.month ?? certificate.month,
          country: updateDto.country ?? certificate.country,
          companyName: updateDto.companyName ?? certificate.companyName,
          standard: updateDto.standard ?? certificate.standard,
        },
      });
      if (duplicate && duplicate.id !== id) {
        throw new ConflictException('Another certificate with this company and standard already exists');
      }
    }

    await this.isoCertificateRepository.update(id, updateDto);
    return this.isoCertificateRepository.findOneBy({ id });
  }

  async remove(id: number) {
    const result = await this.isoCertificateRepository.softDelete(id);
    if (result.affected === 0) throw new NotFoundException(`Certificate with id ${id} not found`);
    return { message: 'Certificate deleted successfully', id };
  }

  //Automatically sets fileUrl and uploadDate based on file path
async bulkImport(baseDir: string, serverUrl: string) {
  try {
    console.log("📁 Scanning:", baseDir);

    baseDir = path.normalize(baseDir);

    if (!fs.existsSync(baseDir)) {
      throw new Error(`Directory not found: ${baseDir}`);
    }

    const items = fs.readdirSync(baseDir);
    const files = items.filter(f => f.toLowerCase().endsWith('.docx'));

    console.log("📄 Found .docx files:", files.length);

    let importedFiles = 0;
    let skippedFiles = 0;

    const parts = baseDir.split(/[\\/]+/);
    const country = parts.pop() || "";
    const month = parts.pop() || "";
    const yearString = parts.pop() || "0";
    const year = parseInt(yearString, 10);

    if (!year || !month || !country) {
      throw new Error("❌ Could not extract YEAR / MONTH / COUNTRY from path.");
    }

   for (const fileName of files) {
  const filePath = path.join(baseDir, fileName);
  const stats = fs.statSync(filePath);

  const nameWithoutExt = path.basename(fileName, '.docx');

  const standardMatch = nameWithoutExt.match(/(HACCP|GMP|9001|1400|50001|27001|14001|45001|22000)/i);
  const standard = standardMatch ? standardMatch[0].toUpperCase() : "";

  let companyName = nameWithoutExt;
  if (standardMatch) {
    companyName = nameWithoutExt.replace(standardMatch[0], '').replace(/[-\s]+$/, '').trim();
  }

  if (!companyName) {
    console.warn("⚠️ Could not parse company name:", fileName);
    skippedFiles++;
    continue;
  }

  const fileUrl = `${serverUrl}/${fileName}`;

  // Check duplicates
  const exists = await this.isoCertificateRepository.findOne({
    where: { year, month, country, companyName, standard },
  });

  if (exists) {
    console.log("⛔ Duplicate skipped:", fileName);
    skippedFiles++;
    continue;
  }

  const cert = this.isoCertificateRepository.create({
    year,
    month,
    country,
    companyName,
    standard,
    fileName,
    fileUrl,
    uploadDate: stats.mtime,
    fileSize: stats.size,
  });

  await this.isoCertificateRepository.save(cert);
  importedFiles++;

  console.log("✅ Imported:", fileName);
}


    return {
      message: "Bulk import completed",
      totalFiles: files.length,
      importedFiles,
      skippedFiles,
    };

  } catch (error) {
    console.error("❌ Bulk import error:", error);
    throw error;
  }
}


}
