const fs = require('fs');
const path = require('path');

class DatabaseService {
  constructor(configPath = './config.json') {
    this.config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    this.dbPath = path.resolve(this.config.database.path);
    this.formsFile = path.join(this.dbPath, this.config.database.forms_file);

    // Ensure database directory exists
    if (!fs.existsSync(this.dbPath)) {
      fs.mkdirSync(this.dbPath, { recursive: true });
    }

    // Initialize database file if it doesn't exist
    if (!fs.existsSync(this.formsFile)) {
      this.initializeDatabase();
    }
  }

  initializeDatabase() {
    const initialData = {
      submissions: [],
      last_updated: new Date().toISOString()
    };
    fs.writeFileSync(this.formsFile, JSON.stringify(initialData, null, 2));
  }

  saveFormSubmission(formData, sidePanelData = null) {
    try {
      const data = this.loadDatabase();
      const submission = {
        id: Date.now().toString(),
        timestamp: new Date().toISOString(),
        formData: formData,
        sidePanelData: sidePanelData || {},
        ip: null, // Will be set by the proxy server
        userAgent: null // Will be set by the proxy server
      };

      data.submissions.push(submission);
      data.last_updated = new Date().toISOString();

      fs.writeFileSync(this.formsFile, JSON.stringify(data, null, 2));
      console.log(`[DATABASE] Form submission saved with ID: ${submission.id}`);
      return submission.id;

    } catch (error) {
      console.error('[DATABASE] Error saving form submission:', error.message);
      throw error;
    }
  }

  loadDatabase() {
    try {
      const data = fs.readFileSync(this.formsFile, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      console.error('[DATABASE] Error loading database:', error.message);
      // Return empty database structure
      return {
        submissions: [],
        last_updated: new Date().toISOString()
      };
    }
  }

  getAllSubmissions() {
    const data = this.loadDatabase();
    return data.submissions;
  }

  getSubmissionById(id) {
    const data = this.loadDatabase();
    return data.submissions.find(sub => sub.id === id);
  }

  updateSubmission(id, updates) {
    try {
      const data = this.loadDatabase();
      const index = data.submissions.findIndex(sub => sub.id === id);

      if (index !== -1) {
        data.submissions[index] = { ...data.submissions[index], ...updates };
        data.last_updated = new Date().toISOString();
        fs.writeFileSync(this.formsFile, JSON.stringify(data, null, 2));
        console.log(`[DATABASE] Submission ${id} updated`);
        return true;
      }

      return false;
    } catch (error) {
      console.error('[DATABASE] Error updating submission:', error.message);
      throw error;
    }
  }
}

module.exports = DatabaseService;
