"use server";

import {prisma} from "@/lib/db/prisma";
import {NotificationType} from "@prisma/client";

type CreateNotificationInput = {
  userId: string;
  tenantId?: string | null;
  type: NotificationType;
  titleAr: string;
  titleEn: string;
  messageAr: string;
  messageEn: string;
  link?: string | null;
};

export async function createNotification(input: CreateNotificationInput) {
  try {
    const notification = await prisma.notification.create({
      data: {
        userId: input.userId,
        tenantId: input.tenantId ?? null,
        type: input.type,
        titleAr: input.titleAr,
        titleEn: input.titleEn,
        messageAr: input.messageAr,
        messageEn: input.messageEn,
        link: input.link ?? null,
        status: "QUEUED"
      }
    });
    return {success: true, id: notification.id};
  } catch {
    return {success: false, id: null};
  }
}

// ─────────────────────────────────────────────────────────
// Convenience helpers
// ─────────────────────────────────────────────────────────

export async function notifyBookingCreated(userId: string, tenantId: string, bookingNumber: string, link?: string) {
  return createNotification({
    userId,
    tenantId,
    type: "BOOKING_CREATED",
    titleAr: "تم إنشاء حجزك",
    titleEn: "Booking Created",
    messageAr: `تم إنشاء حجزك رقم ${bookingNumber} بنجاح وهو قيد المراجعة.`,
    messageEn: `Your booking #${bookingNumber} has been created and is pending review.`,
    link: link ?? null
  });
}

export async function notifyBookingConfirmed(userId: string, tenantId: string, bookingNumber: string, link?: string) {
  return createNotification({
    userId,
    tenantId,
    type: "BOOKING_CONFIRMED",
    titleAr: "تم تأكيد حجزك",
    titleEn: "Booking Confirmed",
    messageAr: `تم تأكيد حجزك رقم ${bookingNumber} بنجاح.`,
    messageEn: `Your booking #${bookingNumber} has been confirmed.`,
    link: link ?? null
  });
}

export async function notifyBookingCancelled(userId: string, tenantId: string, bookingNumber: string, link?: string) {
  return createNotification({
    userId,
    tenantId,
    type: "BOOKING_CANCELLED",
    titleAr: "تم إلغاء حجزك",
    titleEn: "Booking Cancelled",
    messageAr: `تم إلغاء حجزك رقم ${bookingNumber}.`,
    messageEn: `Your booking #${bookingNumber} has been cancelled.`,
    link: link ?? null
  });
}

export async function notifyTenantCreated(userId: string, tenantName: string) {
  return createNotification({
    userId,
    tenantId: null,
    type: "TENANT_CREATED",
    titleAr: "تم إنشاء شركة جديدة",
    titleEn: "New Company Created",
    messageAr: `تمت إضافة الشركة "${tenantName}" إلى المنصة.`,
    messageEn: `The company "${tenantName}" has been added to the platform.`,
    link: "/super-admin/tenants"
  });
}
