import SQLite from 'react-native-sqlite-storage';

const db = SQLite.openDatabase({ name: 'feedback.db', location: 'default' });

// Initialize FeedbackCategory table (full structure from mockDataFlat)
export const initTables = () => {
  db.transaction(tx => {
    // Table for API-fetched question/answer data
    tx.executeSql(`
      CREATE TABLE IF NOT EXISTS FeedbackCategory (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        MenuId INTEGER,
        SurveyId INTEGER,
        SurveyName TEXT,
        CategoryId INTEGER,
        Category TEXT,
        CategorySequence INTEGER,
        QuestionId INTEGER,
        Question TEXT,
        QuestionType TEXT,
        QuestionTypeNew TEXT,
        QEnable BOOLEAN,
        QuestionImageAllow BOOLEAN,
        QuestionImageMandatory BOOLEAN,
        LengthValidation BOOLEAN,
        MinLength INTEGER,
        MaxLength INTEGER,
        OTP BOOLEAN,
        DateRange TEXT,
        QuestionSequence INTEGER,
        AnswerId INTEGER,
        Answer TEXT,
        AnswerSequence INTEGER,
        ImageAllow1 BOOLEAN,
        ImageAllow2 BOOLEAN,
        Image1Mandatory BOOLEAN,
        Image2Mandatory BOOLEAN,
        EnableQuestion TEXT,
        DisableQuestion TEXT,
        ShowCat INTEGER,
        SubCategoryId INTEGER,
        SubCategory TEXT,
        SubCategorySequence INTEGER,
        CalFormula TEXT,
        RefImage TEXT,
        QuestionRefImage TEXT
      );
    `);

    // Table for locally saved user responses
    tx.executeSql(`
      CREATE TABLE IF NOT EXISTS FeedBackLocalTable (
        KEY_ID INTEGER PRIMARY KEY AUTOINCREMENT,
        STORE_ID INTEGER,
        VISIT_DATE NVARCHAR,
        SURVEY_ID INTEGER,
        CATEGORY_ID INTEGER,
        SUB_CATEGORY_ID INTEGER,
        QUESTION NVARCHAR,
        QUESTION_ID INTEGER,
        QUESTION_TYPE NVARCHAR,
        ANSWER NVARCHAR,
        ANSWER_ID INTEGER,
        QuestionImageAllow INTEGER,
        IMAGE_ALLOW1 INTEGER,
        IMAGE1 NVARCHAR,
        IMAGE_ALLOW2 INTEGER,
        IMAGE2 NVARCHAR,
        MULTI_OPTIONS_IDS NVARCHAR,
        IS_DISABLED NVARCHAR,
        IS_ENABLED NVARCHAR,
        MENU_ID INTEGER,
        ADDED_DATE TEXT,
        VerifyOTP INTEGER,
        QUESTION_REF_IMAGE TEXT,
        STATUS NVARCHAR
      );
    `);

    // 

     tx.executeSql(`
      CREATE TABLE IF NOT EXISTS StoreInfoDNALocal (
        KEY_ID INTEGER PRIMARY KEY AUTOINCREMENT,
        VISIT_DATE NVARCHAR ,
        StoreId INTEGER,
        StoreName NVARCHAR,
        ChainName NVARCHAR,
        Address NVARCHAR,
        Pincode NVARCHAR,
        CityName NVARCHAR,
        StateName NVARCHAR,
        StoreType NVARCHAR,
        UPLOAD_STATUS NVARCHAR
      );
    `);
  });
};

// Bulk insert for FeedbackCategory (full schema)
export const bulkInsertData = (tableName, dataArray) => {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(dataArray) || dataArray.length === 0) {
      resolve(true);
      return;
    }

    if (tableName !== 'FeedbackCategory') {
      reject(`Unsupported table: ${tableName}`);
      return;
    }

    const escape = str => (str || '').toString().replace(/'/g, "''");

    const values = dataArray.map(item => `(
      '${item.MenuId}', '${item.SurveyId}', '${escape(item.SurveyName)}',
      '${item.CategoryId}', '${escape(item.Category)}', '${item.CategorySequence}',
      '${item.QuestionId}', '${escape(item.Question)}', '${escape(item.QuestionType)}',
      '${escape(item.QuestionTypeNew)}', '${item.QEnable ? 1 : 0}', '${item.QuestionImageAllow ? 1 : 0}',
      '${item.QuestionImageMandatory ? 1 : 0}', '${item.LengthValidation ? 1 : 0}', '${item.MinLength}',
      '${item.MaxLength}', '${item.OTP ? 1 : 0}', '${escape(item.DateRange)}', '${item.QuestionSequence}',
      '${item.AnswerId}', '${escape(item.Answer)}', '${item.AnswerSequence}',
      '${item.ImageAllow1 ? 1 : 0}', '${item.ImageAllow2 ? 1 : 0}', '${item.Image1Mandatory ? 1 : 0}',
      '${item.Image2Mandatory ? 1 : 0}', '${escape(item.EnableQuestion)}', '${escape(item.DisableQuestion)}',
      '${item.ShowCat}', '${item.SubCategoryId}', '${escape(item.SubCategory)}', '${item.SubCategorySequence}',
      '${escape(item.CalFormula)}', '${escape(item.RefImage)}', '${escape(item.QuestionRefImage)}'
    )`);

    const sql = `
      INSERT INTO FeedbackCategory (
        MenuId, SurveyId, SurveyName, CategoryId, Category, CategorySequence,
        QuestionId, Question, QuestionType, QuestionTypeNew, QEnable, QuestionImageAllow,
        QuestionImageMandatory, LengthValidation, MinLength, MaxLength, OTP, DateRange,
        QuestionSequence, AnswerId, Answer, AnswerSequence, ImageAllow1, ImageAllow2,
        Image1Mandatory, Image2Mandatory, EnableQuestion, DisableQuestion,
        ShowCat, SubCategoryId, SubCategory, SubCategorySequence,
        CalFormula, RefImage, QuestionRefImage
      )
      VALUES ${values.join(',')}
    `;

    db.transaction(tx => {
      tx.executeSql(`DELETE FROM FeedbackCategory`, [], () => {
        tx.executeSql(sql, [], () => {
          console.log(`${tableName} inserted successfully`);
          resolve(true);
        }, (e1, err) => {
          console.log('Insert error:', err);
          reject(err);
        });
      }, (err) => {
        console.log('Delete error:', err);
        reject(err);
      });
    });
  });
};

// Generic SELECT
export const getAllFromTable = (tableName) => {
  return new Promise((resolve, reject) => {
    db.transaction(tx => {
      tx.executeSql(`SELECT * FROM ${tableName}`, [], (tx, results) => {
        const rows = [];
        for (let i = 0; i < results.rows.length; i++) {
          rows.push(results.rows.item(i));
        }
        resolve(rows);
      }, (err) => {
        console.log(`Select error on ${tableName}:`, err);
        reject(err);
      });
    });
  });
};

export default db;