import { PrismaClient } from '@prisma/client';
import EnvVariableHelper from './envVariableHelper';

import PasswordMgmt from './security/passwordMgmt';

const prisma = new PrismaClient();

export function main() {
    const seed = async () => {
        const customerName = 'customer';
        const customerRole = await prisma.role.upsert({
            where: {
                name: customerName,
            },
            update: {},
            create: {
                name: customerName,
            },
        });

        const employeeName = 'employee';
        const employeeRole = await prisma.role.upsert({
            where: {
                name: employeeName,
            },
            update: {},
            create: {
                name: employeeName,
            },
        });

        const username = EnvVariableHelper.VARIABLES.ADMIN_USER;
        const passwordHash = await PasswordMgmt.generatePasswordHash(
            EnvVariableHelper.VARIABLES.ADMIN_PASSWORD
        );

        const admin = await prisma.user.upsert({
            where: {
                username,
            },
            update: {},
            create: {
                username,
                passwordHash,
                profile: {
                    create: {
                        firstname: 'admin',
                        lastname: 'admin',
                    },
                },
                roles: {
                    connect: [{ id: employeeRole.id }],
                },
            },
        });

        //console.log({ admin });
    };

    seed()
        .catch((e) => {
            console.error(e);
            process.exit(1);
        })
        .finally(async () => {
            await prisma.$disconnect();
        });
}
