import fs from "node:fs";
import path from "node:path";
import BetterSqlite3 from "better-sqlite3";
import {drizzle} from "drizzle-orm/better-sqlite3";
import {createHotUpdater} from "@hot-updater/server";
import {drizzleAdapter} from "@hot-updater/server/adapters/drizzle";
import {createMigrator} from "@hot-updater/server/db";
import * as schema from "./hot-updater-schema.mjs";

const file=path.resolve(".drizzle-proof.sqlite");
fs.rmSync(file,{force:true});
const sqlite=new BetterSqlite3(file);
sqlite.pragma("journal_mode = WAL");
sqlite.pragma("foreign_keys = ON");
const db=drizzle(sqlite,{schema});
const hu=createHotUpdater({
  database:drizzleAdapter({db,provider:"sqlite",schema}),
  basePath:"/mobile-updates"
});
const migration=await createMigrator(hu).migrateToLatest({mode:"from-schema",updateSettings:true});
await migration.execute();

const bundle={
  id:"0199aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee",
  platform:"android",
  shouldForceUpdate:false,
  enabled:true,
  fileHash:"abc123",
  gitCommitHash:null,
  message:"drizzle proof",
  channel:"verification/android",
  storageUri:"https://example.invalid/test.zip",
  targetAppVersion:"1.0.0",
  fingerprintHash:null,
  metadata:{proof:true,nested:{ok:1}},
  rolloutCohortCount:1000,
  targetCohorts:["alpha","beta"]
};
await hu.insertBundle(bundle);
const roundTrip=await hu.getBundleById(bundle.id);
if(!roundTrip) throw new Error("roundtrip_missing");
if(roundTrip.enabled!==true||roundTrip.shouldForceUpdate!==false) throw new Error("boolean_roundtrip_failed");
if(roundTrip.metadata?.proof!==true) throw new Error("json_roundtrip_failed");
if(JSON.stringify(roundTrip.targetCohorts)!==JSON.stringify(["alpha","beta"])) throw new Error("cohort_roundtrip_failed");
console.log(JSON.stringify({ok:true,roundTrip},null,2));
sqlite.close();
fs.rmSync(file,{force:true});
fs.rmSync(file+"-wal",{force:true});
fs.rmSync(file+"-shm",{force:true});
