'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { isAuthenticated, signIn, signOut } from '@/lib/auth';
import {
  deleteCategory,
  deleteMessage,
  deleteProduct,
  saveCategory,
  saveProduct,
  saveSettings,
  setMessageRead,
} from '@/lib/db';

export type FormState = { status: 'idle' | 'ok' | 'error'; message?: string };

async function guard() {
  if (!(await isAuthenticated())) {
    throw new Error('Yetkisiz işlem.');
  }
}

function refresh() {
  revalidatePath('/', 'layout');
}

/* ------------------------------- oturum ---------------------------- */

export async function loginAction(_prev: FormState, fd: FormData): Promise<FormState> {
  const email = String(fd.get('email') ?? '');
  const password = String(fd.get('password') ?? '');
  const res = await signIn(email, password);
  if (!res.ok) return { status: 'error', message: res.error };
  redirect('/admin');
}

export async function logoutAction() {
  await signOut();
  redirect('/admin/login');
}

/* ------------------------------ kategori --------------------------- */

export async function saveCategoryAction(_prev: FormState, fd: FormData): Promise<FormState> {
  await guard();
  const id = String(fd.get('id') ?? '');
  const name = String(fd.get('name') ?? '').trim();
  if (!name) return { status: 'error', message: 'Kategori adı zorunlu.' };

  try {
    await saveCategory({
      id: id || undefined,
      name,
      slug: String(fd.get('slug') ?? '').trim() || undefined,
      description: String(fd.get('description') ?? '').trim() || null,
      sort_order: Number(fd.get('sort_order') ?? 99) || 99,
      is_active: fd.get('is_active') === 'on',
    });
    refresh();
    return { status: 'ok', message: 'Kategori kaydedildi.' };
  } catch (e) {
    return { status: 'error', message: (e as Error).message };
  }
}

export async function deleteCategoryAction(fd: FormData) {
  await guard();
  await deleteCategory(String(fd.get('id')));
  refresh();
  redirect('/admin/kategoriler');
}

/* -------------------------------- urun ----------------------------- */

export async function saveProductAction(_prev: FormState, fd: FormData): Promise<FormState> {
  await guard();
  const name = String(fd.get('name') ?? '').trim();
  const category_id = String(fd.get('category_id') ?? '');
  if (!name) return { status: 'error', message: 'Ürün adı zorunlu.' };
  if (!category_id) return { status: 'error', message: 'Kategori seçin.' };

  const rawPrice = String(fd.get('price') ?? '').replace(',', '.').trim();
  const price = rawPrice === '' ? null : Number(rawPrice);
  if (price !== null && Number.isNaN(price)) {
    return { status: 'error', message: 'Fiyat sayı olmalı.' };
  }

  try {
    await saveProduct({
      id: String(fd.get('id') ?? '') || undefined,
      category_id,
      name,
      description: String(fd.get('description') ?? '').trim() || null,
      unit: String(fd.get('unit') ?? '').trim() || null,
      price,
      image_url: String(fd.get('image_url') ?? '').trim() || null,
      is_featured: fd.get('is_featured') === 'on',
      is_active: fd.get('is_active') === 'on',
      sort_order: Number(fd.get('sort_order') ?? 99) || 99,
    });
    refresh();
    return { status: 'ok', message: 'Ürün kaydedildi.' };
  } catch (e) {
    return { status: 'error', message: (e as Error).message };
  }
}

export async function deleteProductAction(fd: FormData) {
  await guard();
  await deleteProduct(String(fd.get('id')));
  refresh();
  redirect('/admin/urunler');
}

/* ------------------------------- ayarlar --------------------------- */

const SETTING_KEYS = [
  'brand_name',
  'tagline',
  'hero_title',
  'hero_subtitle',
  'about_title',
  'about_body',
  'phone',
  'whatsapp',
  'email',
  'address',
  'working_hours',
  'instagram',
  'facebook',
  'map_embed_url',
] as const;

export async function saveSettingsAction(_prev: FormState, fd: FormData): Promise<FormState> {
  await guard();
  const patch: Record<string, string> = {};
  for (const k of SETTING_KEYS) patch[k] = String(fd.get(k) ?? '');
  try {
    await saveSettings(patch);
    refresh();
    return { status: 'ok', message: 'Site ayarları güncellendi.' };
  } catch (e) {
    return { status: 'error', message: (e as Error).message };
  }
}

/* ------------------------------- mesajlar -------------------------- */

export async function toggleMessageAction(fd: FormData) {
  await guard();
  await setMessageRead(String(fd.get('id')), fd.get('is_read') === '1');
  refresh();
}

export async function deleteMessageAction(fd: FormData) {
  await guard();
  await deleteMessage(String(fd.get('id')));
  refresh();
}
