import 'dotenv/config';
import { Types } from 'mongoose';
import MediaModel from '../../models/MediaSchema';
import QRCodeModel from '../../models/QrCode';
import * as fs from 'fs';
import * as path from 'path';
import { FileHandlerUtils } from '../../utils/FileHandlerUtils';

// ========== FIND SINGLE MEDIA ID ===============
export const findMediaById = (id: string) => {
  return MediaModel.findById(id);
};

// ======= FIND QRCODE IMAGE ==========
export const findQrcodeImage = (id: string) => {
  return MediaModel.findOne({ qrcode_id: id }).populate('media_id').lean().exec();
};

// ========= FIND ALL MEDIAS ==============
export const findAllMediaById = (id?: string[]) => {
  return MediaModel.findById(id);
};

// ========== INSERT MEDIA ===============
export const insertMedia = (mediaData: Record<string, any>, baseUrl?: string) => {


  console.log(`============ THIS IS FILE PATH =================`)
  console.log(mediaData.filePath)
  console.log(`============ THIS IS FILE PATH =================`)



  // Normalize filePath to remove leading slash from uploads paths and fix double slashes
  if (mediaData.filePath) {
    mediaData.filePath = mediaData.filePath.replace(/\\/g, '/').replace(/^.*[\/\\]uploads[\/\\]/, 'uploads/').replace(/\/+/g, '/');

    // Generate hostUrl from baseUrl and filePath
    if (baseUrl) {
      const normalizedFilePath = mediaData.filePath.replace(/^\/+/, '');
      mediaData.hostUrl = `${baseUrl}/${normalizedFilePath}`;
    } else {
      // Fallback to environment variable or default
      const defaultBaseUrl = process.env.BASE_URL || process.env.FRONTEND_URL || 'http://localhost:3002';
      const normalizedFilePath = mediaData.filePath.replace(/^\/+/, '');
      mediaData.hostUrl = `${defaultBaseUrl}/${normalizedFilePath}`;
    }
  }
  return MediaModel.create(mediaData);
};


// ========== UPDATE MEDIA ===============
export const updateMedia = async (
  id: string | Types.ObjectId,
  mediaData: {
    originalName?: string;
    filePath?: string;
    mimeType?: string;
    size?: number;
  }
) => {
  // Handle both string and ObjectId types
  const updateQuery = typeof id === 'string'
    ? { _id: id }
    : { _id: id };

  return MediaModel.findOneAndUpdate(updateQuery, mediaData, { new: true });
};

// ========== DELETE MEDIA ===============
export const deleteMedia = async (id: string | Types.ObjectId) => {
  // Find the media record
  const media = await MediaModel.findById(id);

  if (!media) {
    return null;
  }

  // Delete the file from filesystem
  if (media.filePath) {
    try {
      await FileHandlerUtils.deleteFile(media.filePath);
    } catch (error) {
      console.error(`Failed to delete file: ${media.filePath}`, error);
    }
  }

  // Delete the media record from database
  await MediaModel.findByIdAndDelete(id);

  return media;
};

// ========== REPLACE MEDIA ARRAY FOR QRCODE ===============
export const replaceMediaArrayForQrCode = async (
  existingMediaIds: Types.ObjectId[],
  newMediaData: Array<{
    originalName?: string;
    filePath?: string;
    mimeType?: string;
    size?: number;
  }>,
  baseUrl?: string
) => {
  // Delete existing media records and their files from filesystem
  if (existingMediaIds && existingMediaIds.length > 0) {
    // First, fetch the media records to get their file paths
    const existingMedia = await MediaModel.find({ _id: { $in: existingMediaIds } });

    // Delete files from filesystem
    for (const media of existingMedia) {
      if (media.filePath) {
        try {
          await FileHandlerUtils.deleteFile(media.filePath);
        } catch (error) {
          console.error(`Failed to delete file: ${media.filePath}`, error);
          // Continue with other files even if one fails
        }
      }
    }

    // Then delete the media records from database
    await MediaModel.deleteMany({ _id: { $in: existingMediaIds } });
  }

  // Create new media records
  const newMediaIds: Types.ObjectId[] = [];
  for (const mediaItem of newMediaData) {
    const newMedia = await insertMedia(mediaItem, baseUrl);
    if (newMedia) {
      newMediaIds.push(newMedia._id);
    }
  }

  return newMediaIds;
};


