import bcrypt from 'bcrypt';
import { Op, type CreationAttributes, type QueryInterface } from 'sequelize';
import config from '@/shared/config';
import type { Users } from '@/db/models/users';

/** Seed-only env vars are required: the admin account is needed to log in. */
function requiredSeedEnv(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Seeding requires environment variable: ${name}`);
  }
  return value;
}

const ids = [
  '193bf4b5-9f07-4bd5-9a43-e7e41f3e96af',
  'af5a87be-8f9c-4630-902a-37a60b7005ba',
  '5bc531ab-611f-41f3-9373-b7cc5d09c93d',
  'ab4cf9bf-4eef-4107-b73d-9d0274cf69bc',
];

export default {
  up: async (queryInterface: QueryInterface) => {
    const adminHash = bcrypt.hashSync(
      requiredSeedEnv('SEED_ADMIN_PASSWORD'),
      config.bcrypt.saltRounds,
    );
    const userHash = bcrypt.hashSync(
      requiredSeedEnv('SEED_USER_PASSWORD'),
      config.bcrypt.saltRounds,
    );
    const adminEmail = requiredSeedEnv('SEED_ADMIN_EMAIL');
    const createdAt = new Date();
    const updatedAt = new Date();

    const rows: CreationAttributes<Users>[] = [
      {
        id: ids[0],
        firstName: 'Admin',
        email: adminEmail,
        emailVerified: true,
        provider: config.providers.LOCAL,
        password: adminHash,
        createdAt,
        updatedAt,
      },
      {
        id: ids[1],
        firstName: 'John',
        email: 'john@doe.com',
        emailVerified: true,
        provider: config.providers.LOCAL,
        password: userHash,
        createdAt,
        updatedAt,
      },
      {
        id: ids[2],
        firstName: 'Client',
        email: 'client@hello.com',
        emailVerified: true,
        provider: config.providers.LOCAL,
        password: userHash,
        createdAt,
        updatedAt,
      },
      {
        id: ids[3],
        firstName: 'Super Admin',
        email: 'super_admin@flatlogic.com',
        emailVerified: true,
        provider: config.providers.LOCAL,
        password: adminHash,
        createdAt,
        updatedAt,
      },
    ];

    await queryInterface.bulkInsert('users', rows);
  },

  down: async (queryInterface: QueryInterface) => {
    await queryInterface.bulkDelete('users', { id: { [Op.in]: ids } }, {});
  },
};
