const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const webSettingsSchema = new Schema(
  {
    siteName: {
      type: String,
      default: 'Helthstra',
      trim: true,
    },
    siteUrl: {
      type: String,
      default: 'http://localhost:3000',
      trim: true,
    },
    siteEmail: {
      type: String,
      default: 'contact@helthstra.com',
      trim: true,
      lowercase: true,
    },
    sitePhone: {
      type: String,
      default: '',
      trim: true,
    },
    siteAddress: {
      type: String,
      default: '',
      trim: true,
    },
    siteDescription: {
      type: String,
      default: '',
      trim: true,
    },
    maintenanceMode: {
      type: Boolean,
      default: false,
    },
    allowRegistration: {
      type: Boolean,
      default: true,
    },
    enableEmailVerification: {
      type: Boolean,
      default: true,
    },
    defaultUserRole: {
      type: String,
      enum: ['customer', 'admin'],
      default: 'customer',
    },
    timezone: {
      type: String,
      default: 'UTC',
    },
    dateFormat: {
      type: String,
      default: 'DD/MM/YYYY',
    },
    timeFormat: {
      type: String,
      enum: ['12h', '24h'],
      default: '12h',
    },
    currency: {
      type: String,
      default: 'USD',
    },
    currencySymbol: {
      type: String,
      default: '$',
    },
    currencyPosition: {
      type: String,
      enum: ['left', 'right'],
      default: 'left',
    },
    thousandSeparator: {
      type: String,
      default: ',',
    },
    decimalSeparator: {
      type: String,
      default: '.',
    },
    numberOfDecimals: {
      type: Number,
      min: 0,
      max: 4,
      default: 2,
    },
    // Store settings (using siteStore* to match frontend)
    siteStoreName: {
      type: String,
      default: 'Helthstra Store',
      trim: true,
    },
    siteStoreEmail: {
      type: String,
      default: 'store@helthstra.com',
      trim: true,
      lowercase: true,
    },
    siteStorePhone: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreAddress: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreCountry: {
      type: String,
      default: 'India',
      trim: true,
    },
    siteStoreState: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreCity: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreZipCode: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreCurrency: {
      type: String,
      default: 'INR',
      trim: true,
    },
    siteStoreCurrencySymbol: {
      type: String,
      default: '₹',
      trim: true,
    },
    siteStoreTimezone: {
      type: String,
      default: 'Asia/Kolkata',
      trim: true,
    },
    siteStoreLanguage: {
      type: String,
      default: 'en',
      trim: true,
    },
    siteStoreLogo: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreIcon: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreMetaTitle: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreMetaDescription: {
      type: String,
      default: '',
      trim: true,
    },
    siteStoreMetaKeywords: {
      type: String,
      default: '',
      trim: true,
    },
  },
  {
    timestamps: true,
  }
);

// Create or get the single settings document
webSettingsSchema.statics.getSettings = async function() {
  console.log('WebSettings.getSettings(): Fetching settings...');
  try {
    let settings = await this.findOne({});
    
    if (!settings) {
      console.log('No settings found, creating default settings...');
      settings = await this.create({});
      console.log('Default settings created:', JSON.stringify(settings, null, 2));
    } else {
      console.log('Found existing settings:', JSON.stringify(settings, null, 2));
    }
    
    return settings;
  } catch (error) {
    console.error('Error in getSettings:', error);
    throw error;
  }
};

// Update settings
webSettingsSchema.statics.updateSettings = async function(updates) {
  console.log('WebSettings.updateSettings(): Updating with:', JSON.stringify(updates, null, 2));
  
  try {
    let settings = await this.findOne({});
    
    if (!settings) {
      console.log('No settings found, creating new settings with provided updates');
      // Ensure all name fields are in sync when creating
      if (updates.siteStoreName || updates.siteName || updates.storeName) {
        const name = updates.siteStoreName || updates.siteName || updates.storeName;
        updates.siteStoreName = name;
        updates.siteName = name;
        updates.storeName = name;
      }
      settings = await this.create(updates);
      console.log('New settings created:', JSON.stringify(settings, null, 2));
    } else {
      console.log('Found existing settings, updating...');
      console.log('Before update:', JSON.stringify(settings.toObject(), null, 2));
      
      // First update all fields
      Object.assign(settings, updates);
      
      // Then ensure name fields stay in sync
      if ('siteStoreName' in updates || 'siteName' in updates || 'storeName' in updates) {
        // Use the most recently updated name as the source of truth
        const newName = updates.siteStoreName || updates.siteName || updates.storeName ||
                       settings.siteStoreName || settings.siteName || settings.storeName || 'Helthstra';
        
        console.log('Syncing name fields to:', newName);
        
        // Update all name fields to match
        settings.siteStoreName = newName;
        settings.siteName = newName;
        settings.storeName = newName;
        
        // Mark all name fields as modified to ensure they get saved
        settings.markModified('siteStoreName');
        settings.markModified('siteName');
        settings.markModified('storeName');
      }
      
      await settings.save();
      console.log('After update:', JSON.stringify(settings.toObject(), null, 2));
    }
    
    return settings;
  } catch (error) {
    console.error('Error in updateSettings:', error);
    if (error.name === 'ValidationError') {
      console.error('Validation errors:', JSON.stringify(error.errors, null, 2));
    }
    throw error;
  }
};

const WebSettings = mongoose.model('WebSettings', webSettingsSchema);

module.exports = WebSettings;
