import { Injectable, OnApplicationBootstrap, Logger } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { PrismaService } from '../prisma/prisma.service';

type SeedUser = {
  username: string;
  email: string;
  passwordEnvKey: string;
  role: string;
};

const SEED_USERS: SeedUser[] = [
  { username: 'Nadmin', email: 'nadmin@localhost', passwordEnvKey: 'ADMIN_NADMIN_PASSWORD', role: 'admin' },
  { username: 'Padmin', email: 'padmin@localhost', passwordEnvKey: 'ADMIN_PADMIN_PASSWORD', role: 'admin' },
  { username: 'user1',  email: 'user1@localhost',  passwordEnvKey: 'SEED_USER1_PASSWORD',   role: 'user' },
  { username: 'user2',  email: 'user2@localhost',  passwordEnvKey: 'SEED_USER2_PASSWORD',   role: 'user' },
];

@Injectable()
export class AdminBootstrapService implements OnApplicationBootstrap {
  private readonly logger = new Logger(AdminBootstrapService.name);

  constructor(private readonly prisma: PrismaService) {}

  async onApplicationBootstrap() {
    for (const seed of SEED_USERS) {
      const password = process.env[seed.passwordEnvKey];
      if (!password) {
        this.logger.warn(`${seed.passwordEnvKey} not set — skipping ${seed.username}`);
        continue;
      }

      const existing = await this.prisma.user.findUnique({ where: { username: seed.username } });

      if (existing) {
        if (existing.role !== seed.role) {
          await this.prisma.user.update({ where: { id: existing.id }, data: { role: seed.role } });
          this.logger.log(`Updated role for ${seed.username} → ${seed.role}`);
        }
      } else {
        const passwordHash = await bcrypt.hash(password, 12);
        await this.prisma.user.create({
          data: {
            username: seed.username,
            email: seed.email,
            passwordHash,
            role: seed.role,
          },
        });
        this.logger.log(`Created ${seed.role} user: ${seed.username}`);
      }
    }
  }
}
