/**
 * Script rapid: resetare parolă pentru Dorinel Ranga
 */

import { Pool } from "pg"
import { PrismaPg } from "@prisma/adapter-pg"
import { PrismaClient } from "@prisma/client"
import bcrypt from "bcryptjs"
import { randomBytes } from "crypto"
import { readFileSync } from "fs"

const envFile = readFileSync(".env", "utf-8")
for (const line of envFile.split("\n")) {
  const [key, ...rest] = line.split("=")
  if (key && !key.startsWith("#")) {
    process.env[key.trim()] = rest.join("=").trim().replace(/^"|"$/g, "")
  }
}

const pool = new Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const db = new PrismaClient({ adapter })

const chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789"
let password = ""
const bytes = randomBytes(8)
for (let i = 0; i < 8; i++) password += chars[bytes[i] % chars.length]

const email = "dorinel.ranga@kiritescu.ro"

async function main() {
  const hashedPassword = await bcrypt.hash(password, 10)

  const existing = await db.user.findUnique({ where: { email } })
  if (existing) {
    await db.user.update({
      where: { email },
      data: { password: hashedPassword },
    })
    console.log(`✅ Parola a fost resetată cu succes.`)
    console.log(`\n   Nume:     ${existing.name}`)
    console.log(`   Email:    ${email}`)
    console.log(`   Parolă:   ${password}`)
  } else {
    console.log(`❌ Contul cu emailul ${email} nu a fost găsit.`)
  }

  await db.$disconnect()
  await pool.end()
}

main().catch((e) => { console.error("❌ Eroare:", e.message); process.exit(1) })
