'use server';

import { prisma } from '@/lib/db';
import { createSession, deleteSession } from '@/lib/auth';
import bcrypt from 'bcryptjs';
import { revalidatePath } from 'next/cache';

// Auth Actions
export async function login(formData: FormData) {
  const username = formData.get('username') as string;
  const password = formData.get('password') as string;

  if (!username || !password) {
    return { error: 'Kullanıcı adı ve şifre zorunludur' };
  }

  const user = await prisma.user.findUnique({ where: { username } });
  if (!user) {
    return { error: 'Hatalı kullanıcı adı veya şifre' };
  }

  const isValid = await bcrypt.compare(password, user.password);
  if (!isValid) {
    return { error: 'Hatalı kullanıcı adı veya şifre' };
  }

  await createSession(user.id);
  return { success: true };
}

export async function logout() {
  await deleteSession();
}

// Contact Actions
export async function markContactAsRead(id: string) {
  await prisma.contactMessage.update({
    where: { id },
    data: { isRead: true }
  });
}

export async function deleteContact(id: string) {
  await prisma.contactMessage.delete({ where: { id } });
}

// Gallery Actions
export async function addGalleryItem(data: { title: string, category: string, imageUrl: string }) {
  await prisma.gallery.create({ data });
}

export async function deleteGalleryItem(id: string) {
  await prisma.gallery.delete({ where: { id } });
}

// Service Actions
export async function addServiceItem(data: { title: string, description: string, iconUrl?: string }) {
  await prisma.service.create({ data });
}

export async function deleteServiceItem(id: string) {
  await prisma.service.delete({ where: { id } });
}

export async function updateServiceItem(id: string, data: { title: string, description: string, iconUrl?: string }) {
  await prisma.service.update({
    where: { id },
    data
  });
}

// Hero Actions
export async function updateHeroMedia(url: string, type: string) {
  // We only want one hero media. We can delete all and create a new one.
  await prisma.heroMedia.deleteMany({});
  await prisma.heroMedia.create({
    data: { url, type }
  });
  revalidatePath('/', 'layout');
}

// Site Settings Actions
export async function updateSiteSettings(data: {
  logoUrl?: string;
  phone?: string;
  email?: string;
  addressText1?: string;
  addressText2?: string;
  workingHours?: string;
  instagramUrl?: string;
  facebookUrl?: string;
  youtubeUrl?: string;
  whatsappNumber?: string;
}) {
  const existing = await prisma.siteSettings.findFirst();
  if (existing) {
    await prisma.siteSettings.update({
      where: { id: existing.id },
      data
    });
  } else {
    await prisma.siteSettings.create({ data });
  }
}
