import 'dotenv/config';
import MediaModel from '../models/MediaSchema';
import * as fs from 'fs';
import * as fsPromises from 'fs/promises';
import path from 'path';
import {
  MediaModelProps,
  MediaResult,
  FileData,
  UserDataWithMedia,
} from '../types/index';
import { FileHandlerUtils } from './FileHandlerUtils';

export interface InsertMediaOptions {
  file?: Express.Multer.File;
  uploadDir?: string;
  fieldName?: string;
  generatePath?: (file: Express.Multer.File) => string;
  baseUrl?: string;
}

export interface InsertMediaResult {
  mediaId: string;
  filePath: string;
  originalName: string;
  mimeType: string;
  size: number;
  mediaRecord: any;
}

export class MediaUtils {
  /**
   * Dynamic insertMedia component - Use this in any API to handle media uploads
   * @param options Configuration options for media insertion
   * @returns Media result with ID, path, and record details
   *
   * @example
   * // Basic usage with default path
   * const media = await MediaUtils.insertMedia({ file: req.file });
   *
   * @example
   * // Custom upload directory
   * const media = await MediaUtils.insertMedia({
   *   file: req.file,
   *   uploadDir: 'uploads/documents'
   * });
   *
   * @example
   * // Custom path generation
   * const media = await MediaUtils.insertMedia({
   *   file: req.file,
   *   generatePath: (file) => `uploads/custom/${Date.now()}-${file.filename}`
   * });
   */
  public static async insertMedia(
    options: InsertMediaOptions
  ): Promise<InsertMediaResult | null> {
    const { file, uploadDir, generatePath, baseUrl } = options;

    if (!file) {
      return null;
    }

    try {
      // Multer already saved the file to the correct location (file.path is absolute)
      // We need to convert it to a relative path for database storage
      let filePath: string;

      if (generatePath) {
        filePath = generatePath(file);
      } else if (uploadDir) {
        // When uploadDir is provided, construct relative path from uploadDir and filename
        // Multer already saved the file, so we just need the relative path structure
        const cleanFilename = file.filename.replace(/^\/+/, '');
        filePath = `${uploadDir}/${cleanFilename}`;
      } else {
        // Convert multer's absolute file.path to relative path
        const absolutePath = file.path.replace(/\\/g, '/');
        const cwd = process.cwd().replace(/\\/g, '/');

        // Convert absolute path to relative path
        if (absolutePath.startsWith(cwd)) {
          filePath = absolutePath.substring(cwd.length).replace(/^\/+/, '');
        } else {
          // Fallback: extract relative path from absolute path
          // Handle 'uploads/' pattern (used in both production and development)
          const uploadsIndex = absolutePath.indexOf('/uploads/');

          if (uploadsIndex !== -1) {
            // uploads/profile-pictures/...
            filePath = absolutePath.substring(uploadsIndex + 1);
          } else {
            // Try to find uploads in the path
            const uploadsMatch = absolutePath.match(/[\\/]uploads[\\/](.+)$/);
            if (uploadsMatch) {
              filePath = `uploads/${uploadsMatch[1]}`;
            } else {
              // Last resort: use filename from multer
              filePath = `uploads/${file.filename}`;
            }
          }
        }
      }

      // Debug logging in development
      if (process.env.NODE_ENV === 'development') {
        console.log('MediaUtils.insertMedia - File path conversion:');
        console.log('  Original file.path:', file.path);
        console.log('  Converted filePath:', filePath);
        console.log('  Upload directory:', uploadDir);
      }

      // Remove leading slash from uploads paths and normalize double slashes
      filePath = filePath.replace(/^\/uploads/, 'uploads').replace(/\/+/g, '/');

      // Multer already saved the file to the correct location (file.path is absolute)
      // Verify the file exists at the location multer saved it
      if (!file.path) {
        throw new Error('File path is missing - multer may not have processed the file');
      }

      if (!fs.existsSync(file.path)) {
        console.error('File not found at multer path:', file.path);
        console.error('File details:', {
          originalname: file.originalname,
          filename: file.filename,
          fieldname: file.fieldname,
          mimetype: file.mimetype,
          size: file.size,
        });
        throw new Error(`Uploaded file not found at: ${file.path}`);
      }

      // Verify file size matches
      const stats = fs.statSync(file.path);
      if (stats.size !== file.size) {
        console.warn(`File size mismatch: expected ${file.size}, got ${stats.size}`);
      }

      // Generate hostUrl from baseUrl and filePath
      let hostUrl: string | undefined;
      if (baseUrl) {
        const normalizedFilePath = filePath.replace(/^\/+/, '');
        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 = filePath.replace(/^\/+/, '');
        hostUrl = `${defaultBaseUrl}/${normalizedFilePath}`;
      }

      // Create media record in database
      const mediaData: MediaModelProps = {
        originalName: file.originalname,
        filePath: filePath,
        hostUrl: hostUrl,
        mimeType: file.mimetype,
        size: file.size.toString(),
      };

      const media = await MediaModel.create(mediaData);

      // Note: We don't delete file.path because multer already saved it to the final location
      // The file is already in uploads/profile-pictures/ (both production and development)

      return {
        mediaId: media._id.toString(),
        filePath: filePath,
        originalName: file.originalname,
        mimeType: file.mimetype,
        size: file.size,
        mediaRecord: media,
      };
    } catch (error) {
      throw new Error(`Failed to insert media: ${error}`);
    }
  }

  public static async createMediaRecord(
    fileData?: FileData,
    filePath?: string,
    hostUrl?: string
  ): Promise<MediaResult | null> {
    if (!fileData || !filePath) {
      return null;
    }

    try {
      // Generate hostUrl if not provided
      let finalHostUrl: string | undefined = hostUrl;
      if (!finalHostUrl && filePath) {
        const defaultBaseUrl = process.env.BASE_URL || process.env.FRONTEND_URL || 'http://localhost:3002';
        const normalizedFilePath = filePath.replace(/^\/+/, '');
        finalHostUrl = `${defaultBaseUrl}/${normalizedFilePath}`;
      }

      const mediaData: MediaModelProps = {
        originalName: fileData.originalname,
        filePath: filePath,
        hostUrl: finalHostUrl,
        mimeType: fileData.mimetype,
        size: fileData.size.toString(),
      };

      const media = await MediaModel.create(mediaData);

      return {
        mediaId: media._id,
        filePath: filePath,
        mediaRecord: media,
      };
    } catch (error) {
      throw new Error(`Failed to create media record: ${error}`);
    }
  }

  public static addMediaToUserData(
    userData: UserDataWithMedia,
    mediaResult: MediaResult | null
  ): UserDataWithMedia {
    if (mediaResult) {
      userData.profile_picture = mediaResult.filePath;
      userData.media_id = mediaResult.mediaId;
    }
    return userData;
  }

  public static async handleUserMedia(
    userData: UserDataWithMedia,
    fileData?: FileData,
    filePath?: string,
    hostUrl?: string
  ): Promise<UserDataWithMedia> {
    // If a new file is provided, always create a new media record
    // This ensures media_id is updated to point to the new file
    // The old media record will be cleaned up separately in the service layer
    if (fileData && filePath) {
      const mediaResult = await this.createMediaRecord(fileData, filePath, hostUrl);
      return this.addMediaToUserData(userData, mediaResult);
    }

    // If no file is provided, return userData as-is
    return userData;
  }

  public static async deleteMediaRecord(mediaId: string): Promise<void> {
    try {
      // First get the media record to get the file path
      const mediaRecord = await MediaModel.findById(mediaId);

      if (mediaRecord && mediaRecord.filePath) {
        // Delete the physical file
        await this.deletePhysicalFile(mediaRecord.filePath);
      }

      // Delete the database record
      await MediaModel.findByIdAndDelete(mediaId);
    } catch (error) {
      throw new Error(`Failed to delete media record: ${error}`);
    }
  }

  public static async deletePhysicalFile(filePath: string): Promise<void> {
    try {
      // Use the new FileHandlerUtils for safe file deletion
      const deleted = await FileHandlerUtils.deleteFile(filePath);

      if (!deleted) {
        console.warn(`File not found or could not be deleted: ${filePath}`);
      }
    } catch (error) {
      console.error(`Failed to delete physical file ${filePath}:`, error);
      // Don't throw error for file deletion failures to avoid breaking the main operation
    }
  }

  public static async getMediaRecord(mediaId: string): Promise<any> {
    try {
      return await MediaModel.findById(mediaId);
    } catch (error) {
      throw new Error(`Failed to get media record: ${error}`);
    }
  }
}
