import { PrismaClient } from "../src/generated/prisma";
import { PrismaMariaDb } from "@prisma/adapter-mariadb";
import bcrypt from "bcryptjs";
import "dotenv/config";

// Configuration de l'adaptateur pour le script
const adapter = new PrismaMariaDb({
  host: "localhost",
  port: 3306,
  user: "root",
  password: "",
  database: "diabetix_001",
});

const prisma = new PrismaClient({ adapter });

const moments = [
  { key: "FASTING", hour: 7, baseMin: 0.85, baseMax: 1.25 },
  { key: "BEFORE_LUNCH", hour: 11, baseMin: 0.8, baseMax: 1.2 },
  { key: "AFTER_LUNCH", hour: 14, baseMin: 1.1, baseMax: 1.8 },
  { key: "BEFORE_DINNER", hour: 18, baseMin: 0.8, baseMax: 1.2 },
  { key: "AFTER_DINNER", hour: 21, baseMin: 1.1, baseMax: 1.8 },
  { key: "BEDTIME", hour: 23, baseMin: 1.0, baseMax: 1.4 },
] as const;

function rand(min: number, max: number) {
  return min + Math.random() * (max - min);
}

async function main() {
  console.log("🌱 Début du seeding avec nouveaux moments...");

  // 1. Nettoyage
  await prisma.reading.deleteMany();
  await prisma.patient.deleteMany();
  await prisma.user.deleteMany();

  // 2. Création de l'utilisateur de test
  const passwordHash = await bcrypt.hash("password123", 10);
  const user = await prisma.user.create({
    data: {
      email: "jeremy@test.com",
      name: "Jeremy",
      passwordHash,
      plan: "PREMIUM",
    },
  });

  await prisma.patient.create({
    data: {
      userId: user.id,
      firstName: "Jeremy",
      lastName: "Test",
      diabetesType: "TYPE1",
      treatment: "Insuline",
      birthDate: new Date("1990-01-01"),
    },
  });

  // 3. Génération de 30 jours de relevés réalistes
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const data: { userId: string; measuredAt: Date; moment: string; value: number; notes: string | null }[] = [];

  for (let day = 29; day >= 0; day--) {
    for (const m of moments) {
      // Pour simuler la vie réelle, on ne prend pas tous les relevés chaque jour
      if (m.key !== "FASTING" && Math.random() < 0.3) continue;

      const d = new Date(today.getTime() - day * 86_400_000);
      d.setHours(m.hour, Math.floor(Math.random() * 45), 0, 0);
      let value = rand(m.baseMin, m.baseMax);
      
      // Quelques valeurs aberrantes
      if (Math.random() < 0.04) value = rand(0.5, 0.68);
      if (Math.random() < 0.04) value = rand(1.85, 2.3);
      
      data.push({
        userId: user.id,
        measuredAt: d,
        moment: m.key,
        value: Math.round(value * 100) / 100,
        notes: null,
      });
    }
  }

  await prisma.reading.createMany({ data });
  console.log(`✓ Base MySQL synchronisée avec les nouveaux moments.`);
  console.log(`✓ ${data.length} relevés générés.`);
  console.log("✅ Seeding terminé !");
}

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