import "server-only"; import { eq } from "drizzle-orm"; import { appDb, schema } from "@/lib/appdb"; import { PROFIL_SEMASI, profilTemizle, type DanismanProfili, type ProfilAlani, } from "@/lib/danisman-profil"; /** Kullanıcının danışman profili; satır yoksa boş nesne. Bozuk alanlar düşer. */ export async function profilGetir(userId: string): Promise { const satir = await appDb.query.danismanProfil.findFirst({ where: eq(schema.danismanProfil.userId, userId), columns: { alanlar: true }, }); return profilTemizle(satir?.alanlar); } /** * Tek alanı yazar (deger null → alan silinir). Değer şemadan geçmezse hata * fırlatır; çağıran taraf (araç) bunu modele "kaydedilmedi" diye döner. */ export async function profilAlanYaz( userId: string, alan: ProfilAlani, deger: unknown, ): Promise { const mevcut = await profilGetir(userId); const yeni: Record = { ...mevcut }; if (deger === null || deger === undefined) { delete yeni[alan]; } else { const dogrulama = PROFIL_SEMASI.shape[alan].safeParse(deger); if (!dogrulama.success) { throw new Error(`Geçersiz değer: ${alan}`); } yeni[alan] = dogrulama.data; } const alanlar = PROFIL_SEMASI.parse(yeni); const now = new Date(); await appDb .insert(schema.danismanProfil) .values({ userId, alanlar, updatedAt: now }) .onConflictDoUpdate({ target: schema.danismanProfil.userId, set: { alanlar, updatedAt: now }, }); return alanlar; } export async function profilSil(userId: string): Promise { await appDb .delete(schema.danismanProfil) .where(eq(schema.danismanProfil.userId, userId)); }