import 'dotenv/config'
import { getDb } from './client.js'
import { hashPassword } from '../services/password.service.js'

const sql = getDb()

const seed = async () => {
  // Create super_admin role
  const [role] = await sql`
    INSERT INTO roles (name, permissions)
    VALUES (
      'super_admin',
      ${sql.json({
        mitra: ['create', 'read', 'update', 'delete'],
        control_center_users: ['create', 'read', 'update', 'delete'],
        config: ['read', 'update'],
        roles: ['create', 'read', 'update', 'delete'],
      })}
    )
    ON CONFLICT (name) DO UPDATE SET permissions = EXCLUDED.permissions
    RETURNING id
  `

  const email = process.env.ADMIN_EMAIL || process.env.SEED_ADMIN_EMAIL || 'admin@halobestie.com'
  const password = process.env.ADMIN_PASSWORD || process.env.SEED_ADMIN_PASSWORD || 'ChangeMe123!'
  const passwordHash = await hashPassword(password)

  await sql`
    INSERT INTO control_center_users (email, display_name, role_id, password_hash)
    VALUES (${email}, 'Super Admin', ${role.id}, ${passwordHash})
    ON CONFLICT (email) DO UPDATE SET password_hash = EXCLUDED.password_hash
  `

  console.log(`Seed complete. Admin: ${email}`)
  await sql.end()
}

seed().catch((err) => {
  console.error('Seed failed:', err)
  process.exit(1)
})
