const { PrismaClient, RoomType } = require('@prisma/client');
const bcrypt = require('bcryptjs');

const prisma = new PrismaClient();

async function hashPassword(password) {
    return bcrypt.hash(password, 10);
}

async function main() {
    console.log('🌱 Seeding database with base configuration...\n');

    // ==================== ROLES (Required) ====================
    console.log('📋 Creating Roles...');
    const rolesData = [
        {
            name: 'Facility Owner',
            description: 'Full access to all features and settings',
            permissions: { admin: true, all: true },
            isSystem: true
        },
        {
            name: 'Manager',
            description: 'Operational control and reporting',
            permissions: {
                users: { view: true, manage: true },
                tasks: { view: true, manage: true, assign: true },
                inventory: { view: true, manage: true },
                reports: { view: true, export: true },
                visitors: { view: true, manage: true },
                compliance: { view: true }
            },
            isSystem: true
        },
        {
            name: 'Grower',
            description: 'Plant care and daily operations',
            permissions: {
                tasks: { view: true, complete: true },
                inventory: { view: true },
                batches: { view: true, update: true },
                rooms: { view: true }
            },
            isSystem: true
        },
        {
            name: 'Worker',
            description: 'Basic task completion and logging',
            permissions: {
                tasks: { view: true, complete: true },
                timeclock: { view: true, punch: true }
            },
            isSystem: true
        },
        {
            name: 'Viewer',
            description: 'Read-only access to dashboards',
            permissions: {
                dashboard: { view: true },
                reports: { view: true }
            },
            isSystem: true
        }
    ];

    for (const r of rolesData) {
        const existing = await prisma.role.findUnique({ where: { name: r.name } });
        if (!existing) {
            await prisma.role.create({ data: r });
            console.log(`  ✓ Created Role: ${r.name}`);
        }
    }

    const ownerRole = await prisma.role.findUnique({ where: { name: 'Facility Owner' } });

    // ==================== ADMIN USER (Required) ====================
    console.log('\n👤 Creating Admin User...');
    const adminExists = await prisma.user.findUnique({ where: { email: 'admin@runfoo.run' } });
    if (!adminExists) {
        const passwordHash = await hashPassword('password123');
        await prisma.user.create({
            data: {
                email: 'admin@runfoo.run',
                passwordHash,
                name: 'Travis (Owner)',
                role: 'OWNER',
                roleId: ownerRole?.id,
                rate: 100.00
            }
        });
        console.log('  ✓ Created Admin: admin@runfoo.run / password123');
    }

    console.log('\n✨ Base seeding complete!\n');
    console.log('Login: admin@runfoo.run / password123');
    console.log('\nFor demo data, run: npm run seed:demo');
}

main()
    .catch((e) => {
        console.error('Seeding failed:', e);
        process.exit(1);
    })
    .finally(async () => {
        await prisma.$disconnect();
    });
