'use server';

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

// 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 } });
}
