'use server'

// ===== Enums =====
// لا يوجد تعدادات (Enums) خاصة مطلوبة لهذه الصفحة لتصديرها للواجهة الأمامية

// ===== Data Structures =====
export interface AccountUserItem {
  account_user_id: string       // data-from: account_user-id
  account_user_account: string  // data-from: account_user-account
  account_user_email: string    // data-from: account_user-email
}

// ===== Input / Output =====
export interface RegisterAdminInput {
  account_user_account: string
  account_user_email: string
  account_user_password: string
}

export interface RegisterAdminOutput {
  account_user_id: string
}

// ===== Imports =====
import prisma from '@/tools/prisma'
import { withResult, hashPassword } from '@/backend/action_utils'

// ===== Actions =====

/**
 * تسجيل مدير جديد للنظام
 * صفحة عامة (GUEST) لا تتطلب تسجيل الدخول
 */
export const registerAdmin = withResult(async (input: RegisterAdminInput): Promise<RegisterAdminOutput> => {
  const account = input.account_user_account?.trim()
  const email = input.account_user_email?.trim()
  const password = input.account_user_password

  // 1. التحقق من الحقول الإلزامية
  if (!account || !email || !password) {
    throw new Error('يرجى تعبئة جميع الحقول الإلزامية')
  }

  // 2. التحقق من صيغة البريد الإلكتروني
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email)) {
    throw new Error('صيغة البريد الإلكتروني غير صحيحة')
  }

  // 3. التحقق من عدم تكرار اسم المستخدم
  const existingAccount = await prisma.account_user.findUnique({
    where: { account: account }
  })
  if (existingAccount) {
    throw new Error('اسم المستخدم مستخدم مسبقاً، يرجى اختيار اسم آخر')
  }

  // 4. التحقق من عدم تكرار البريد الإلكتروني
  const existingEmail = await prisma.account_user.findUnique({
    where: { email: email }
  })
  if (existingEmail) {
    throw new Error('البريد الإلكتروني مستخدم لحساب آخر')
  }

  // 5. تشفير كلمة المرور
  const hashedPassword = hashPassword(password)

  // 6. إنشاء حساب المدير
  const newUser = await prisma.account_user.create({
    data: {
      account: account,
      email: email,
      password: hashedPassword,
      role: 'ADMIN', // تحديد الصلاحية الثابتة للمدير
    }
  })

  return {
    account_user_id: newUser.id
  }
})