/**
 * Data fetching functions untuk PUBLIC pages.
 * File ini TIDAK mengimport auth — aman digunakan di server components manapun.
 */
import { prisma } from './prisma';

export async function getKabinetAktif() {
    try {
        const data = await prisma.kabinet.findFirst({
            where: { isAktif: true },
            orderBy: { createdAt: 'desc' },
            // Note: In Supabase it fetched ProgramUnggulan, but they are not linked by FK in schema.
            // Wait, ProgramUnggulan is standalone. I'll just return Kabinet and fetch ProgramUnggulan separately.
        });
        
        if (!data) return null;
        
        // Fetch Program Unggulan
        const programUnggulan = await prisma.programUnggulan.findMany({
            orderBy: { createdAt: 'asc' }
        });
        
        return {
            ...data,
            ProgramUnggulan: programUnggulan
        };
    } catch {
        return null;
    }
}

export async function getProkerByBidang(bidang: string) {
    try {
        return await prisma.programKerja.findMany({
            where: { bidang }
        });
    } catch {
        return [];
    }
}

export async function getPengurusByDivisi(divisi: string) {
    try {
        return await prisma.pengurus.findMany({
            where: { divisi },
            orderBy: { jabatan: 'asc' }
        });
    } catch {
        return [];
    }
}

export async function getAllPengurus() {
    try {
        return await prisma.pengurus.findMany({
            orderBy: [
                { angkatan: 'asc' },
                { divisi: 'desc' }
            ]
        });
    } catch {
        return null;
    }
}

export async function getAllBidang() {
    try {
        return await prisma.bidangLembaga.findMany({
            orderBy: { name: 'asc' }
        });
    } catch {
        return [];
    }
}

export async function getBidangBySlug(slug: string) {
    try {
        return await prisma.bidangLembaga.findUnique({
            where: { slug }
        });
    } catch {
        return null;
    }
}

export async function getAllShortLinks() {
    try {
        return await prisma.shortLink.findMany({
            orderBy: { createdAt: 'desc' }
        });
    } catch {
        return [];
    }
}

export async function getPublicShortLinks() {
    try {
        return await prisma.shortLink.findMany({
            where: { isPublic: true },
            orderBy: { createdAt: 'desc' }
        });
    } catch {
        return [];
    }
}

export async function getShortLinkBySlug(slug: string) {
    try {
        return await prisma.shortLink.findUnique({
            where: { slug }
        });
    } catch {
        return null;
    }
}

export async function getShortLinksByUserId(userId: string) {
    try {
        return await prisma.shortLink.findMany({
            where: { userId },
            orderBy: { createdAt: 'desc' }
        });
    } catch {
        return [];
    }
}

export async function getAllUsers() {
    try {
        return await prisma.user.findMany({
            orderBy: { name: 'asc' }
        });
    } catch {
        return [];
    }
}

export async function getProfilAktif() {
    try {
        return await prisma.profil.findFirst({
            where: { isAktif: true }
        });
    } catch {
        return null;
    }
}

// ==========================================
// MATA KULIAH KURIKULUM UPI (UNTUK KINETIK)
// ==========================================
export async function getAllMataKuliah() {
    try {
        return await prisma.mataKuliah.findMany({
            orderBy: [
                { semester_rekomendasi: 'asc' },
                { nama: 'asc' }
            ]
        });
    } catch (err: any) {
        console.error("CATCH: Gagal menarik data matkul:", err.message);
        return [];
    }
}

// ==========================================
// BEARR LINKS (BANK SOAL, EBOOK, DSB)
// ==========================================
export type BearrKategori = 'bank_soal' | 'ebook' | 'aplikasi' | 'responsi' | 'referensi';
export type BearrTipeUrl = 'drive' | 'form' | 'list' | 'wa' | 'lainnya';

export interface BearrLink {
    id: string;
    kategori: BearrKategori;
    judul: string;
    deskripsi: string | null;
    url: string;
    tipe_url: BearrTipeUrl;
    is_active: boolean;
    urutan: number;
    created_at: Date;
    updated_at: Date;
}

export async function getAllBearrLinks(onlyActive = true): Promise<BearrLink[]> {
    try {
        const query: any = {
            orderBy: [
                { urutan: 'asc' },
                { created_at: 'asc' }
            ]
        };

        if (onlyActive) {
            query.where = { is_active: true };
        }

        return (await prisma.bearrLink.findMany(query)) as unknown as BearrLink[];
    } catch (err: any) {
        console.error("CATCH: Gagal menarik data BEARR:", err.message);
        return [];
    }
}

// ==========================================
// ORBIT - Marketplace Barang Bekas Mahasiswa
// ==========================================
export type OrbitKategori = 'buku' | 'jas_lab' | 'alat_ukur' | 'alat_tulis' | 'elektronik' | 'lainnya';
export type OrbitKondisi = 'baru' | 'baik' | 'cukup' | 'butuh_perbaikan';

export interface OrbitItem {
    id: string;
    judul: string;
    deskripsi: string | null;
    harga: number;               // 0 = gratis/hibah
    kondisi: OrbitKondisi;
    kategori: OrbitKategori;
    foto_url: string | null;
    penjual_nama: string;
    penjual_instagram: string;   // username IG tanpa @
    is_terjual: boolean;
    is_active: boolean;
    created_at: Date;
    updated_at: Date;
}

export async function getOrbitItems(onlyActive = true): Promise<OrbitItem[]> {
    try {
        const query: any = {
            orderBy: { created_at: 'desc' }
        };

        if (onlyActive) {
            query.where = { is_active: true };
        }

        return (await prisma.orbitItem.findMany(query)) as unknown as OrbitItem[];
    } catch (err: any) {
        console.error("CATCH: Gagal menarik data ORBIT:", err.message);
        return [];
    }
}

// ==========================================
// FLUKS - Etalase Digital Danusan Ekobis
// ==========================================
export type FluksKategori = 'buku' | 'makanan' | 'aplikasi' | 'merchandise' | 'layanan' | 'lainnya';
export type FluksTipeLInk = 'instagram' | 'whatsapp' | 'lainnya';
export type FluksStok = 'tersedia' | 'terbatas' | 'habis';

export interface FluksItem {
    id: string;
    nama: string;
    deskripsi: string | null;
    harga: number;
    kategori: FluksKategori;
    foto_url: string | null;
    link_order: string | null;
    tipe_link: FluksTipeLInk;
    stok: FluksStok;
    badge: string | null;
    is_active: boolean;
    urutan: number;
    created_at: Date;
    updated_at: Date;
}

export interface FluksConfig {
    id: string;
    form_order_url: string;
    catatan: string | null;
    updated_at: Date;
}

export async function getFluksItems(onlyActive = true): Promise<FluksItem[]> {
    try {
        const query: any = {
            orderBy: [
                { urutan: 'asc' },
                { created_at: 'desc' }
            ]
        };

        if (onlyActive) {
            query.where = { is_active: true };
        }

        return (await prisma.fluksItem.findMany(query)) as unknown as FluksItem[];
    } catch (err: any) {
        console.error("CATCH: Gagal menarik data FLUKS:", err.message);
        return [];
    }
}

export async function getFluksConfig(): Promise<FluksConfig | null> {
    try {
        return (await prisma.fluksConfig.findFirst()) as unknown as FluksConfig | null;
    } catch {
        return null;
    }
}

// ==========================================
// DATA PARLEMEN (DPM)
// ==========================================

export async function getSemuaAnggotaParlemen() {
    try {
        return await prisma.anggotaParlemen.findMany({
            orderBy: [
                { angkatan: 'asc' },
                { komisi: 'asc' }
            ]
        });
    } catch {
        return [];
    }
}

export async function getSemuaProdukMumas() {
    try {
        return await prisma.produkMumas.findMany({
            orderBy: { createdAt: 'desc' }
        });
    } catch {
        return [];
    }
}

// ==========================================
// DATA ACARA
// ==========================================

export async function getAcaraAktif() {
    try {
        if (prisma.acara && typeof prisma.acara.findMany === 'function') {
            return await prisma.acara.findMany({
                where: { status: 'AKTIF' },
                orderBy: { createdAt: 'desc' }
            });
        }
        // Fallback for Next.js reload issue
        return await prisma.$queryRaw`SELECT * FROM Acara WHERE status = 'AKTIF' ORDER BY createdAt DESC`;
    } catch {
        return [];
    }
}

export async function getAcaraBySlug(slug: string) {
    try {
        if (prisma.acara && typeof prisma.acara.findUnique === 'function') {
            return await prisma.acara.findUnique({
                where: { slug }
            });
        }
        // Fallback for Next.js reload issue
        const res: any[] = await prisma.$queryRaw`SELECT * FROM Acara WHERE slug = ${slug} LIMIT 1`;
        return res.length > 0 ? res[0] : null;
    } catch {
        return null;
    }
}
