'use server';

import { prisma } from '@/lib/db';
import { getSession } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import bcrypt from 'bcryptjs';

async function requireAuth() {
  const session = await getSession();
  if (!session) redirect('/admin/login');
}

export async function createUser(formData: FormData) {
  await requireAuth();

  const username = formData.get('username') as string;
  const password = formData.get('password') as string;
  const confirmPassword = formData.get('confirmPassword') as string;

  if (!username || !password) return;
  if (password !== confirmPassword) return;
  if (password.length < 6) return;

  const exists = await prisma.user.findUnique({ where: { username } });
  if (exists) return;

  const hashed = await bcrypt.hash(password, 10);
  await prisma.user.create({
    data: { username, password: hashed },
  });

  revalidatePath('/admin/users');
}

export async function deleteUser(formData: FormData) {
  await requireAuth();

  const id = formData.get('id') as string;
  if (!id) return;

  // En az 1 kullanıcı kalsın
  const count = await prisma.user.count();
  if (count <= 1) return;

  await prisma.user.delete({ where: { id } });
  revalidatePath('/admin/users');
}

export async function changePassword(formData: FormData) {
  await requireAuth();

  const userId = formData.get('userId') as string;
  const newPassword = formData.get('newPassword') as string;
  const confirmPassword = formData.get('confirmPassword') as string;

  if (!userId || !newPassword) return;
  if (newPassword !== confirmPassword) return;
  if (newPassword.length < 6) return;

  const hashed = await bcrypt.hash(newPassword, 10);
  await prisma.user.update({
    where: { id: userId },
    data: { password: hashed },
  });

  revalidatePath('/admin/users');
}
