/**
 * Manuel kredi tanımlama (havale/EFT alan müşteri veya test için).
 *
 *   pnpm exec tsx scripts/kredi-tanimla.ts <email> <paket|topup>
 *
 * İdempotent DEĞİLDİR — her çalıştırma yeni bir "sipariş" yaratır ve kredi ekler.
 */
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { appDb, schema } from "../src/lib/appdb";
import { grantCredits, URUNLER } from "../src/lib/credits";

async function main() {
  const [email, productArg] = process.argv.slice(2);
  const product = productArg as "paket" | "topup";
  if (!email || !(product in URUNLER)) {
    console.error(
      "Kullanım: tsx scripts/kredi-tanimla.ts <email> <paket|topup>",
    );
    process.exit(1);
  }

  const user = await appDb.query.user.findFirst({
    where: eq(schema.user.email, email),
  });
  if (!user) {
    console.error(`Kullanıcı bulunamadı: ${email}`);
    process.exit(1);
  }

  const urun = URUNLER[product];
  const orderId = randomUUID();
  await appDb.insert(schema.orders).values({
    id: orderId,
    userId: user.id,
    product,
    amountKurus: urun.amountKurus,
    credits: urun.credits,
    status: "paid",
    iyzicoPaymentId: "MANUEL",
    createdAt: new Date(),
    paidAt: new Date(),
  });
  await grantCredits({
    userId: user.id,
    delta: urun.credits,
    reason: product === "paket" ? "purchase" : "topup",
    refId: orderId,
    setHasPaket: product === "paket",
  });

  console.log(
    `OK: ${email} → +${urun.credits} kredi (${product}), sipariş ${orderId}`,
  );
}

main();
