"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDb = getDb;
exports.connectDB = connectDB;
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const portfolio_1 = require("../data/portfolio");
const DB_DIR = path_1.default.join(process.cwd(), "data");
const DB_PATH = path_1.default.join(DB_DIR, "bot-jdt.db");
let db;
function getDb() {
    return db;
}
function connectDB() {
    if (!fs_1.default.existsSync(DB_DIR))
        fs_1.default.mkdirSync(DB_DIR, { recursive: true });
    db = new better_sqlite3_1.default(DB_PATH);
    db.pragma("journal_mode = WAL");
    migrateServicesSchema();
    db.exec(`
    CREATE TABLE IF NOT EXISTS users (
      telegram_id   INTEGER PRIMARY KEY,
      username      TEXT,
      first_name    TEXT NOT NULL,
      last_name     TEXT,
      is_subscribed INTEGER NOT NULL DEFAULT 1,
      joined_at     TEXT NOT NULL DEFAULT (datetime('now')),
      last_active   TEXT NOT NULL DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS leads (
      id            INTEGER PRIMARY KEY AUTOINCREMENT,
      telegram_id   INTEGER NOT NULL,
      username      TEXT,
      name          TEXT NOT NULL,
      phone_number  TEXT,
      service_type  TEXT NOT NULL,
      project_name  TEXT NOT NULL,
      features      TEXT NOT NULL,
      deadline      TEXT NOT NULL,
      budget        TEXT NOT NULL,
      status        TEXT NOT NULL DEFAULT 'new',
      is_hot        INTEGER NOT NULL DEFAULT 0,
      created_at    TEXT NOT NULL DEFAULT (datetime('now')),
      admin_note    TEXT
    );

    CREATE TABLE IF NOT EXISTS service_categories (
      id          INTEGER PRIMARY KEY AUTOINCREMENT,
      slug        TEXT NOT NULL UNIQUE,
      icon        TEXT NOT NULL,
      name        TEXT NOT NULL,
      description TEXT NOT NULL DEFAULT '',
      sort_order  INTEGER NOT NULL DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS services (
      id            INTEGER PRIMARY KEY AUTOINCREMENT,
      category_slug TEXT NOT NULL,
      slug          TEXT NOT NULL UNIQUE,
      icon          TEXT NOT NULL,
      name          TEXT NOT NULL,
      description   TEXT NOT NULL,
      price         TEXT NOT NULL,
      features      TEXT NOT NULL DEFAULT '[]',
      is_active     INTEGER NOT NULL DEFAULT 1,
      sort_order    INTEGER NOT NULL DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS portfolios (
      id             INTEGER PRIMARY KEY AUTOINCREMENT,
      title          TEXT NOT NULL,
      category       TEXT NOT NULL,
      description    TEXT NOT NULL,
      tech           TEXT NOT NULL,
      demo_url       TEXT,
      media_file_id  TEXT,
      media_type     TEXT DEFAULT 'photo',
      created_at     TEXT NOT NULL DEFAULT (datetime('now'))
    );
  `);
    seedServiceCategories();
    seedServices();
    migrateBotPackages();
    seedPortfolios();
    console.log(`✅ SQLite terhubung: ${DB_PATH}`);
}
// Ganti paket bot lama dengan paket Bot Media & Bot Payment baru
function migrateBotPackages() {
    const hasOld = db
        .prepare("SELECT COUNT(*) as n FROM services WHERE slug = 'bot_basic'")
        .get();
    if (hasOld.n === 0)
        return; // sudah pakai paket baru, skip
    db.prepare("DELETE FROM services WHERE category_slug = 'bot'").run();
    const insert = db.prepare("INSERT INTO services (category_slug, slug, icon, name, description, price, features, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    db.transaction(() => {
        // ── 🎬 Bot Media ─────────────────────────────────────────────────────────
        insert.run("bot", "bot_media_starter", "🎬", "Bot Media — Starter", "Cocok untuk pemula yang ingin memulai bot media sharing sederhana.", "Beli Putus: Rp 100.000 | Sewa: Rp 40.000/bln (termasuk hosting)", JSON.stringify([
            "Upload & kelola media video",
            "1 kategori media",
            "Auto-delete pesan video (2 jam)",
            "Deep link unik per media",
            "Panel admin via Telegram",
            "Pesan welcome kustom",
            "Force subscribe 1 channel",
            "Protect content (anti-forward)",
        ]), 0);
        insert.run("bot", "bot_media_pro", "🎬", "Bot Media — Professional", "Solusi lengkap untuk channel media dengan manajemen user dan broadcast.", "Beli Putus: Rp 200.000 | Sewa: Rp 60.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Starter",
            "Kategori media tidak terbatas",
            "Template caption video & channel kustom",
            "Statistik views per media",
            "Manajemen user (ban/unban)",
            "Force subscribe multi channel",
            "Broadcast pesan ke semua user",
            "Statistik bot lengkap",
            "Log aktivitas ke channel",
            "Backup database otomatis",
            "Maintenance mode",
        ]), 1);
        insert.run("bot", "bot_media_enterprise", "🎬", "Bot Media — Enterprise", "Fitur penuh untuk bisnis skala besar dengan sistem broadcast template canggih.", "Beli Putus: Rp 400.000 | Sewa: Rp 95.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Professional",
            "Sistem template broadcast CRUD",
            "Template dengan foto/video",
            "Tombol inline kustom per template",
            "Preview broadcast sebelum kirim",
            "Owner-only hapus template",
            "Donasi via Telegram Stars ⭐",
            "Total pengguna bot di welcome",
            "Pencarian media (/search)",
            "Tombol welcome kustom",
            "Source code penuh",
            "Prioritas support",
        ]), 2);
        // ── 💳 Bot Payment ────────────────────────────────────────────────────────
        insert.run("bot", "bot_payment_starter", "💳", "Bot Payment — Starter", "Bot membership sederhana untuk jual akses grup VIP via transfer manual.", "Beli Putus: Rp 100.000 | Sewa: Rp 40.000/bln (termasuk hosting)", JSON.stringify([
            "Jual maksimal 3 paket VIP",
            "Pembayaran QRIS / DANA",
            "User kirim bukti foto bayar",
            "Admin approve / tolak manual",
            "Invite link otomatis setelah approve",
            "Panel admin via Telegram",
            "Kelola info QRIS & nomor DANA",
            "Banner promosi kustom",
        ]), 3);
        insert.run("bot", "bot_payment_pro", "💳", "Bot Payment — Professional", "Solusi lengkap dengan promo, multi-paket, dan broadcast ke semua user.", "Beli Putus: Rp 250.000 | Sewa: Rp 60.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Starter",
            "Paket VIP tidak terbatas",
            "Beli beberapa/semua paket sekaligus",
            "Kode promo diskon nominal & persen",
            "Kuota pemakaian kode promo",
            "Manajemen admin",
            "Broadcast pesan ke semua user",
            "Log transaksi user",
        ]), 4);
        insert.run("bot", "bot_payment_enterprise", "💳", "Bot Payment — Enterprise", "Fitur penuh termasuk layanan VS multi-admin dan source code lengkap.", "Beli Putus: Rp 450.000 | Sewa: Rp 95.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Professional",
            "Jual layanan VS per admin",
            "Foto & caption VS kustom per admin",
            "Harga VS bisa diatur sendiri",
            "Approve VS via owner & admin",
            "Multi-admin dengan VS masing-masing",
            "Statistik transaksi lengkap",
            "Invite link sekali pakai",
            "Source code penuh",
            "Prioritas support",
        ]), 5);
    })();
    console.log("🔄 Migrasi: 6 paket Bot Media & Bot Payment berhasil ditambahkan.");
}
// Hapus tabel services lama (schema berbeda) sebelum buat yang baru
function migrateServicesSchema() {
    const hasOldSchema = db
        .prepare("SELECT COUNT(*) as n FROM pragma_table_info('services') WHERE name='packages'")
        .get();
    if (hasOldSchema.n > 0) {
        db.exec("DROP TABLE IF EXISTS services;");
        console.log("🔄 Migrasi: tabel services lama dihapus, akan dibuat ulang dengan schema baru.");
    }
}
function seedServiceCategories() {
    const count = db.prepare("SELECT COUNT(*) as n FROM service_categories").get().n;
    if (count > 0)
        return;
    const insert = db.prepare("INSERT INTO service_categories (slug, icon, name, description, sort_order) VALUES (?, ?, ?, ?, ?)");
    db.transaction(() => {
        insert.run("web", "🌐", "Website", "Landing Page, Company Profile, hingga Ecommerce", 0);
        insert.run("apk", "📱", "Mobile App (APK)", "Aplikasi Android untuk berbagai kebutuhan bisnis", 1);
        insert.run("bot", "🤖", "Bot Telegram", "Bot otomatis dari sederhana hingga AI chatbot", 2);
    })();
    console.log("✅ Seeded 3 kategori layanan");
}
function seedServices() {
    const count = db.prepare("SELECT COUNT(*) as n FROM services").get().n;
    if (count > 0)
        return;
    const insert = db.prepare("INSERT INTO services (category_slug, slug, icon, name, description, price, features, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    db.transaction(() => {
        // ── Web ───────────────────────────────────────────────────────────────────
        insert.run("web", "landing", "📄", "Landing Page", "Halaman promosi satu halaman yang menarik untuk personal branding, produk digital, atau event.", "Rp 300.000 – Rp 1.500.000", JSON.stringify(["1 halaman responsif", "Desain premium", "Form kontak", "WhatsApp button", "Domain .my.id tersedia", "Hosting tersedia"]), 0);
        insert.run("web", "company", "🏢", "Company Profile", "Website profesional untuk UMKM, sekolah, yayasan, dan perusahaan.", "Rp 500.000 – Rp 3.000.000", JSON.stringify(["3–10 halaman", "CMS Admin Panel", "Blog / Berita", "SEO dasar", "Domain + Hosting tersedia", "Garansi bug fix"]), 1);
        insert.run("web", "ecommerce", "🛒", "Ecommerce", "Toko online lengkap dengan produk, keranjang, checkout, dan sistem pembayaran.", "Rp 1.500.000 – Rp 7.500.000", JSON.stringify(["Katalog produk", "Keranjang & checkout", "Payment gateway Midtrans", "WhatsApp order", "Admin panel", "Laporan penjualan"]), 2);
        // ── APK ───────────────────────────────────────────────────────────────────
        insert.run("apk", "apk_simple", "📱", "APK Simple", "Aplikasi Android ringan dengan fitur dasar, cocok untuk UMKM dan keperluan internal.", "Rp 1.000.000", JSON.stringify(["5–8 screen", "Firebase backend", "Android only", "Upload Play Store"]), 0);
        insert.run("apk", "apk_standard", "📱", "APK Standard", "Aplikasi Android lengkap dengan backend custom dan dashboard web admin.", "Rp 4.000.000", JSON.stringify(["10–15 screen", "Backend custom", "Dashboard web admin", "Upload Play Store", "Notifikasi push"]), 1);
        insert.run("apk", "apk_advanced", "📱", "APK Advanced", "Aplikasi Android kompleks dengan fitur premium, integrasi maps, payment, dan chat.", "Mulai Rp 7.500.000", JSON.stringify(["Fitur kompleks", "Maps / payment / chat", "Backend microservices", "Multi-platform ready", "Maintenance 3 bulan"]), 2);
        // ── 🎬 Bot Media ──────────────────────────────────────────────────────────
        insert.run("bot", "bot_media_starter", "🎬", "Bot Media — Starter", "Cocok untuk pemula yang ingin memulai bot media sharing sederhana.", "Beli Putus: Rp 100.000 | Sewa: Rp 40.000/bln (termasuk hosting)", JSON.stringify([
            "Upload & kelola media video", "1 kategori media",
            "Auto-delete pesan video (2 jam)", "Deep link unik per media",
            "Panel admin via Telegram", "Pesan welcome kustom",
            "Force subscribe 1 channel", "Protect content (anti-forward)",
        ]), 0);
        insert.run("bot", "bot_media_pro", "🎬", "Bot Media — Professional", "Solusi lengkap untuk channel media dengan manajemen user dan broadcast.", "Beli Putus: Rp 200.000 | Sewa: Rp 60.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Starter", "Kategori media tidak terbatas",
            "Template caption video & channel kustom", "Statistik views per media",
            "Manajemen user (ban/unban)", "Force subscribe multi channel",
            "Broadcast pesan ke semua user", "Statistik bot lengkap",
            "Log aktivitas ke channel", "Backup database otomatis", "Maintenance mode",
        ]), 1);
        insert.run("bot", "bot_media_enterprise", "🎬", "Bot Media — Enterprise", "Fitur penuh untuk bisnis skala besar dengan sistem broadcast template canggih.", "Beli Putus: Rp 400.000 | Sewa: Rp 95.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Professional", "Sistem template broadcast CRUD",
            "Template dengan foto/video", "Tombol inline kustom per template",
            "Preview broadcast sebelum kirim", "Owner-only hapus template",
            "Donasi via Telegram Stars ⭐", "Total pengguna bot di welcome",
            "Pencarian media (/search)", "Tombol welcome kustom",
            "Source code penuh", "Prioritas support",
        ]), 2);
        // ── 💳 Bot Payment ────────────────────────────────────────────────────────
        insert.run("bot", "bot_payment_starter", "💳", "Bot Payment — Starter", "Bot membership sederhana untuk jual akses grup VIP via transfer manual.", "Beli Putus: Rp 100.000 | Sewa: Rp 40.000/bln (termasuk hosting)", JSON.stringify([
            "Jual maksimal 3 paket VIP", "Pembayaran QRIS / DANA",
            "User kirim bukti foto bayar", "Admin approve / tolak manual",
            "Invite link otomatis setelah approve", "Panel admin via Telegram",
            "Kelola info QRIS & nomor DANA", "Banner promosi kustom",
        ]), 3);
        insert.run("bot", "bot_payment_pro", "💳", "Bot Payment — Professional", "Solusi lengkap dengan promo, multi-paket, dan broadcast ke semua user.", "Beli Putus: Rp 250.000 | Sewa: Rp 60.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Starter", "Paket VIP tidak terbatas",
            "Beli beberapa/semua paket sekaligus",
            "Kode promo diskon nominal & persen", "Kuota pemakaian kode promo",
            "Manajemen admin", "Broadcast pesan ke semua user", "Log transaksi user",
        ]), 4);
        insert.run("bot", "bot_payment_enterprise", "💳", "Bot Payment — Enterprise", "Fitur penuh termasuk layanan VS multi-admin dan source code lengkap.", "Beli Putus: Rp 450.000 | Sewa: Rp 95.000/bln (termasuk hosting)", JSON.stringify([
            "Semua fitur Professional", "Jual layanan VS per admin",
            "Foto & caption VS kustom per admin", "Harga VS bisa diatur sendiri",
            "Approve VS via owner & admin", "Multi-admin dengan VS masing-masing",
            "Statistik transaksi lengkap", "Invite link sekali pakai",
            "Source code penuh", "Prioritas support",
        ]), 5);
    })();
    console.log("✅ Seeded 9 paket layanan (3 kategori × 3 paket)");
}
function seedPortfolios() {
    const count = db.prepare("SELECT COUNT(*) as n FROM portfolios").get().n;
    if (count > 0)
        return;
    const insert = db.prepare(`
    INSERT INTO portfolios (title, category, description, tech, demo_url, media_file_id, media_type)
    VALUES (@title, @category, @description, @tech, @demoUrl, NULL, 'photo')
  `);
    const insertMany = db.transaction(() => {
        for (const item of portfolio_1.portfolioData) {
            insert.run({
                title: item.title,
                category: item.category,
                description: item.description,
                tech: item.tech.join(", "),
                demoUrl: item.demoUrl || null,
            });
        }
    });
    insertMany();
    console.log(`✅ Seeded ${portfolio_1.portfolioData.length} portfolio awal`);
}
