import db from '../src/database/models/index.js';
const { sequelize } = db;

async function updateDealerCodesTable() {
    console.log('🔄 Checking and updating dealer_codes table schema...');
    
    try {
        // Add applicationId
        await sequelize.query(`
            DO $$ 
            BEGIN 
                IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='dealer_codes' AND column_name='applicationId') THEN
                    ALTER TABLE dealer_codes ADD COLUMN "applicationId" UUID REFERENCES applications(id);
                END IF;
                
                IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='dealer_codes' AND column_name='salesCode') THEN
                    ALTER TABLE dealer_codes ADD COLUMN "salesCode" VARCHAR(255);
                END IF;

                IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='dealer_codes' AND column_name='serviceCode') THEN
                    ALTER TABLE dealer_codes ADD COLUMN "serviceCode" VARCHAR(255);
                END IF;

                IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='dealer_codes' AND column_name='gmaCode') THEN
                    ALTER TABLE dealer_codes ADD COLUMN "gmaCode" VARCHAR(255);
                END IF;

                IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='dealer_codes' AND column_name='gearCode') THEN
                    ALTER TABLE dealer_codes ADD COLUMN "gearCode" VARCHAR(255);
                END IF;

                IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='dealer_codes' AND column_name='sapMasterId') THEN
                    ALTER TABLE dealer_codes ADD COLUMN "sapMasterId" VARCHAR(255);
                END IF;
            END $$;
        `);

        console.log('✅ dealer_codes table schema updated successfully.');
        process.exit(0);
    } catch (error) {
        console.error('❌ Error updating dealer_codes table:', error);
        process.exit(1);
    }
}

updateDealerCodesTable();
