import db from '../database/models/index.js';
import { v4 as uuidv4 } from 'uuid';

const seedQuestionnaire = async () => {
    try {
        console.log('Seeding Questionnaire...');
        console.log('DB Keys:', Object.keys(db));
        console.log('QuestionnaireOption defined?', !!db.QuestionnaireOption);

        // Ensure database schema is up to date
        // Skipping sync because dev server holds locks
        // console.log('Syncing database...');
        // await db.sequelize.sync({ alter: true });

        // Deactivate existing questionnaires
        await db.Questionnaire.update({ isActive: false }, { where: {} });

        // Create new questionnaire
        const questionnaire = await db.Questionnaire.create({
            id: uuidv4(),
            version: 'v1.0',
            isActive: true
        });

        console.log(`Created Questionnaire: ${questionnaire.id}`);

        const questions = [
            // Section 1: Basic Information (0 Score)
            {
                text: "Email",
                type: "email",
                section: "Basic Information",
                options: null,
                weight: 0,
                order: 1
            },
            {
                text: "Name",
                type: "text",
                section: "Basic Information",
                options: null,
                weight: 0,
                order: 2
            },
            {
                text: "Current Location",
                type: "text",
                section: "Basic Information",
                options: null,
                weight: 0,
                order: 3
            },
            {
                text: "Location Applied For",
                type: "text",
                section: "Basic Information",
                options: null,
                weight: 0,
                order: 4
            },
            {
                text: "State (Applied for)",
                type: "select",
                section: "Basic Information",
                options: [
                    { text: "Andaman & Nicobar", score: 0 },
                    { text: "Andhra Pradesh", score: 0 },
                    { text: "Arunachal Pradesh", score: 0 },
                    { text: "Assam", score: 0 },
                    { text: "Bihar", score: 0 },
                    { text: "Chandigarh", score: 0 },
                    { text: "Chhattisgarh", score: 0 },
                    { text: "Delhi & NCR", score: 0 },
                    { text: "Goa", score: 0 },
                    { text: "Gujarat", score: 0 },
                    { text: "Himachal Pradesh", score: 0 },
                    { text: "Haryana", score: 0 },
                    { text: "Jammu & Kashmir", score: 0 },
                    { text: "Jharkhand", score: 0 },
                    { text: "Karnataka", score: 0 },
                    { text: "Kerala", score: 0 },
                    { text: "Ladakh", score: 0 },
                    { text: "Madhya Pradesh", score: 0 },
                    { text: "Maharashtra", score: 0 },
                    { text: "Mizoram", score: 0 },
                    { text: "Meghalaya", score: 0 },
                    { text: "Manipur", score: 0 },
                    { text: "Nagaland", score: 0 },
                    { text: "Odisha", score: 0 },
                    { text: "Puducherry", score: 0 },
                    { text: "Punjab", score: 0 },
                    { text: "Rajasthan", score: 0 },
                    { text: "Sikkim", score: 0 },
                    { text: "Tamilnadu", score: 0 },
                    { text: "Telangana", score: 0 },
                    { text: "Tripura", score: 0 },
                    { text: "Uttar Pradesh", score: 0 },
                    { text: "Uttarakhand", score: 0 },
                    { text: "West Bengal", score: 0 }
                ],
                weight: 0,
                order: 5
            },
            {
                text: "Contact Number",
                type: "text",
                section: "Basic Information",
                options: null,
                weight: 0,
                order: 6
            },
            {
                text: "Age",
                type: "number",
                section: "Basic Information",
                options: null,
                weight: 0,
                order: 7
            },
            {
                text: "Are you an existing dealer/vendor of Royal Enfield?",
                type: "yesno",
                section: "Basic Information",
                options: [
                    { text: "Yes", score: 0 },
                    { text: "No", score: 0 }
                ],
                weight: 0,
                order: 8
            },

            // Section 2: Profile & Background (Scoring Starts)
            {
                text: "Educational Qualification",
                type: "select",
                section: "Profile & Background",
                options: [
                    { text: "Under Graduate", score: 2 },
                    { text: "Graduate", score: 3 },
                    { text: "Post Graduate", score: 5 }
                ],
                weight: 5, // Max possible
                order: 8
            },
            {
                text: "What is your Personal Networth",
                type: "select",
                section: "Financials",
                options: [
                    { text: "Less than 2 Crores", score: 3 },
                    { text: "Between 2 - 5 Crores", score: 6 },
                    { text: "Between 5 - 10 Crores", score: 9 },
                    { text: "Between 10 - 15 Crores", score: 12 },
                    { text: "Greater than 15 Crores", score: 15 }
                ],
                weight: 15,
                order: 9
            },
            {
                text: "Are you a native of the Proposed Location?",
                type: "select",
                section: "Location",
                options: [
                    { text: "Native", score: 10 },
                    { text: "Willing to Relocate", score: 5 },
                    { text: "Will manage Remotely", score: 0 }
                ],
                weight: 10,
                order: 10
            },
            {
                text: "Why do you want to partner with Royal Enfield?",
                type: "select",
                section: "Strategy",
                options: [
                    { text: "Absence of Royal Enfield in the particular location and presence of opportunity", score: 2 },
                    { text: "Passionate about the brand", score: 2 },
                    { text: "Experience in the automobile business and would like to expand with Royal Enfield", score: 5 }
                ],
                weight: 5,
                order: 12
            },
            {
                text: "Who will be the partners in proposed company?",
                type: "select",
                section: "Business Structure",
                options: [
                    { text: "Immediate Family", score: 5 },
                    { text: "Extended Family", score: 3 },
                    { text: "Friends", score: 2 },
                    { text: "Proprietorship", score: 5 }
                ],
                weight: 5,
                order: 13
            },
            {
                text: "Who will be managing the Royal Enfield dealership",
                type: "select",
                section: "Business Structure",
                options: [
                    { text: "I will be managing full time", score: 10 },
                    { text: "I will be managing with my partners", score: 7 },
                    { text: "I will hire a manager full time and oversee the operations", score: 5 }
                ],
                weight: 10,
                order: 14
            },
            {
                text: "Proposed Firm Type",
                type: "select",
                section: "Business Structure",
                options: [
                    { text: "Proprietorship", score: 3 },
                    { text: "Partnership", score: 3 },
                    { text: "Limited Liability partnership", score: 3 },
                    { text: "Private Limited Company", score: 5 }
                ],
                weight: 5,
                order: 15
            },
            {
                text: "What are you currently doing?",
                type: "select",
                section: "Experience",
                options: [
                    { text: "Running automobile dealership", score: 10 },
                    { text: "Running another business not in automobile field", score: 5 },
                    { text: "Presently working, willing to resign and handle business", score: 5 },
                    { text: "Currently not working and looking for business opportunities", score: 2 }
                ],
                weight: 10,
                order: 16
            },
            {
                text: "Do you own a property in proposed location?",
                type: "select",
                section: "Location",
                options: [
                    { text: "Yes", score: 10 },
                    { text: "No, will rent a location in the desired location", score: 5 }
                ],
                weight: 10,
                order: 17
            },
            {
                text: "How are you planning to invest in the Royal Enfield business",
                type: "select",
                section: "Financials",
                options: [
                    { text: "I will be investing my own funds", score: 10 },
                    { text: "I will invest partially and get the rest from the bank", score: 7 },
                    { text: "I will be requiring complete funds from the bank", score: 3 }
                ],
                weight: 10,
                order: 18
            },
            {
                text: "What are your plans of expansion with RE?",
                type: "select",
                section: "Strategy",
                options: [
                    { text: "Willing to expand with the help of partners", score: 2 },
                    { text: "Willing to expand by myself", score: 5 },
                    { text: "No plans for expansion", score: 0 }
                ],
                weight: 5,
                order: 19
            },
            {
                text: "Will you be expanding to any other automobile OEM in the future?",
                type: "yesno",
                section: "Strategy",
                options: [
                    { text: "Yes", score: 0 },
                    { text: "No", score: 4 }
                ],
                weight: 4,
                order: 20
            },
            {
                text: "Do you own a Royal Enfield ?",
                type: "select",
                section: "Brand Loyalty",
                options: [
                    { text: "Yes, it is registered in my name", score: 3 },
                    { text: "Yes, it is registered to my immediate family member", score: 2 },
                    { text: "Not at the moment but owned it earlier", score: 1 },
                    { text: "No", score: 0 }
                ],
                weight: 3,
                order: 21
            },
            {
                text: "Do you go for long leisure rides",
                type: "select",
                section: "Brand Loyalty",
                options: [
                    { text: "Yes, with the Royal Enfield riders", score: 3 },
                    { text: "Yes, with other brands", score: 2 },
                    { text: "No", score: 0 }
                ],
                weight: 3,
                order: 22
            },
            {
                text: "What special initiatives do you plan to implement if selected as business partner for Royal Enfield ?",
                type: "textarea",
                section: "Strategy",
                options: null,
                weight: 0,
                order: 23
            },
            {
                text: "Please elaborate your present business/employment.",
                type: "textarea",
                section: "Experience",
                options: null,
                weight: 0,
                order: 24
            }
        ];

        for (const q of questions) {
            const questionId = uuidv4();
            await db.QuestionnaireQuestion.create({
                id: questionId,
                questionnaireId: questionnaire.id,
                sectionName: q.section,
                questionText: q.text,
                inputType: q.type,
                options: null, // Legacy field
                isMandatory: true,
                weight: q.weight,
                order: q.order
            });

            // If question has options, seed them into QuestionnaireOption table
            if (q.options && Array.isArray(q.options) && q.options.length > 0) {
                console.log(`Seeding options for question: ${q.text}`);

                if (!db.QuestionnaireOption) {
                    console.error('CRITICAL: db.QuestionnaireOption is undefined!');
                    console.log('Available models:', Object.keys(db));
                }

                const optionRecords = q.options.map((opt, idx) => ({
                    id: uuidv4(),
                    questionId: questionId,
                    optionText: opt.text,
                    score: opt.score,
                    order: idx + 1
                }));
                const OptionModel = db.sequelize.models.QuestionnaireOption || db.QuestionnaireOption;

                console.log(`[DEBUG] Question: "${q.text}"`);
                console.log(`[DEBUG] OptionModel type: ${typeof OptionModel}`);
                console.log(`[DEBUG] OptionModel keys: ${OptionModel ? Object.keys(OptionModel).slice(0, 5) : 'null'}`);
                console.log(`[DEBUG] bulkCreate type: ${OptionModel ? typeof OptionModel.bulkCreate : 'undefined'}`);

                if (!OptionModel) {
                    throw new Error(`QuestionnaireOption model not found in sequelize.models or db object`);
                }

                try {
                    await OptionModel.bulkCreate(optionRecords);
                    console.log(`[DEBUG] Success seeding options for "${q.text}"`);
                } catch (innerErr: any) {
                    console.error(`[DEBUG] Failed to seed options for "${q.text}"`);
                    console.error('Error Name:', innerErr.name);
                    console.error('Error Message:', innerErr.message);
                    if (innerErr.parent) {
                        console.error('Parent Error:', innerErr.parent);
                    }
                    if (innerErr.original) {
                        console.error('Original Error:', innerErr.original);
                    }
                    throw innerErr;
                }
            }
        }

        console.log(`Seeded questions and options successfully.`);
        process.exit(0);

    } catch (error) {
        console.error('Error seeding questionnaire:', error);
        process.exit(1);
    }
};

seedQuestionnaire();
