import Doctor from '../models/Doctor';
import User from '../models/User';

interface UploadProfileImageData {
  userId: string;
  filePath: string;
}

interface UploadSignatureData {
  userId: string;
  filePath: string;
}

export class UploadService {
  private toPublicUrl(filePath: string): string {
    // Convert local file paths to API-accessible public upload paths.
    const normalized = filePath.replace(/\\/g, '/');
    const marker = '/public/uploads/';
    const markerIndex = normalized.lastIndexOf(marker);
    if (markerIndex >= 0) {
      return `/api/uploads/${normalized.slice(markerIndex + marker.length)}`;
    }
    const apiUploadsIndex = normalized.lastIndexOf('/api/uploads/');
    if (apiUploadsIndex >= 0) {
      return normalized.slice(apiUploadsIndex);
    }
    const uploadsIndex = normalized.lastIndexOf('/uploads/');
    if (uploadsIndex >= 0) {
      return `/api${normalized.slice(uploadsIndex)}`;
    }
    return normalized;
  }

  /**
   * Upload image and return storable path (public URL)
   */
  async uploadPatientImage(filePath: string) {
    if (!filePath) {
      throw new Error('No file uploaded');
    }

    const publicPath = this.toPublicUrl(filePath);

    return {
      message: 'Image uploaded successfully',
      filePath: publicPath
    };
  }

  /**
   * Upload and save profile image
   */
  async uploadProfileImage(data: UploadProfileImageData) {
    const { userId, filePath } = data;

    if (!userId) {
      throw new Error('User ID is required');
    }

    if (!filePath) {
      throw new Error('No file uploaded');
    }

    const publicPath = this.toPublicUrl(filePath);

    // Update User model
    const user = await User.findByIdAndUpdate(
      userId,
      { profileImage: publicPath },
      { new: true }
    );

    if (!user) {
      throw new Error('User not found');
    }

    return {
      message: 'Profile image uploaded successfully',
      filePath: publicPath,
      user: {
        profileImage: user.profileImage
      }
    };
  }

  /**
   * Upload and save signature
   */
  async uploadSignature(data: UploadSignatureData) {
    const { userId, filePath } = data;

    if (!userId) {
      throw new Error('User ID is required');
    }

    if (!filePath) {
      throw new Error('No file uploaded');
    }

    const publicPath = this.toPublicUrl(filePath);

    // Find or create Doctor profile
    let doctor = await Doctor.findOne({ userId });

    if (!doctor) {
      doctor = new Doctor({
        userId,
        isDentist: false,
        signatureUrl: publicPath
      });
      await doctor.save();
    } else {
      doctor.signatureUrl = publicPath;
      await doctor.save();
    }

    return {
      message: 'Signature uploaded successfully',
      filePath: publicPath,
      doctor: {
        signatureUrl: doctor.signatureUrl
      }
    };
  }
  /**
   * Upload clinical record file
   */
  async uploadClinicalFile(filePath: string, originalName: string) {
    if (!filePath) {
      throw new Error('No file uploaded');
    }

    const publicPath = this.toPublicUrl(filePath);

    return {
      message: 'File uploaded successfully',
      filePath: publicPath,
      originalName
    };
  }
}

export default new UploadService();
