require('dotenv').config();
const mysql = require('mysql2/promise');

// Database connection configuration
const dbConfig = {
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'masm_app'
};

const incidentTypes = [
    'Assault',
    'Diabetes',
    'Stroke',
    'Heart Attack',
    'Asthma',
    'Over Dose',
    'Convulsions',
    'Drowning',
    'Accident',
    'Burns',
    'Gun Shot',
    'Maternity'
];

async function seedIncidentTypes() {
    let connection;
    try {
        console.log('Connecting to database...');
        connection = await mysql.createConnection(dbConfig);
        console.log('Connected successfully!');

        // Check if incident_type table exists
        const [tables] = await connection.query(`
            SELECT TABLE_NAME 
            FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = ? 
            AND TABLE_NAME = 'incident_type'
        `, [dbConfig.database]);

        if (tables.length === 0) {
            console.error('❌ Table incident_type does not exist. Please run the migration first.');
            process.exit(1);
        }

        console.log('Seeding incident types...');
        let inserted = 0;
        let skipped = 0;

        for (const typeName of incidentTypes) {
            try {
                await connection.query(
                    'INSERT INTO incident_type (name) VALUES (?)',
                    [typeName]
                );
                console.log(`✓ Inserted: ${typeName}`);
                inserted++;
            } catch (error) {
                if (error.code === 'ER_DUP_ENTRY') {
                    console.log(`  Skipped (already exists): ${typeName}`);
                    skipped++;
                } else {
                    throw error;
                }
            }
        }

        console.log(`\n✅ Seeding completed!`);
        console.log(`   Inserted: ${inserted} incident types`);
        console.log(`   Skipped: ${skipped} incident types (already exist)`);

    } catch (error) {
        console.error('❌ Seeding failed:', error.message);
        if (error.code === 'ER_BAD_DB_ERROR') {
            console.error(`\nDatabase '${dbConfig.database}' does not exist.`);
        } else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
            console.error('\nAccess denied. Please check your database credentials in .env file.');
        }
        process.exit(1);
    } finally {
        if (connection) {
            await connection.end();
            console.log('\nDatabase connection closed.');
        }
    }
}

// Run the seeding
seedIncidentTypes();

