/**
 * Notification Tracking Utilities
 * 
 * This file provides helper functions to automatically track and create notifications
 * for various application events like appointments, prescriptions, payments, etc.
 */

import { http } from './api';

// ─── Type Definitions ───

export type NotificationCategory = 'APPOINTMENT' | 'PRESCRIPTION' | 'PAYMENT' | 'SUBSCRIPTION' | 'SYSTEM';
export type NotificationAction = 
    | 'APPOINTMENT_BOOKED'
    | 'APPOINTMENT_CONFIRMED'
    | 'APPOINTMENT_CANCELLED'
    | 'APPOINTMENT_RESCHEDULED'
    | 'APPOINTMENT_REMINDER'
    | 'PRESCRIPTION_ISSUED'
    | 'PRESCRIPTION_READY'
    | 'PAYMENT_RECEIVED'
    | 'PAYMENT_FAILED'
    | 'SUBSCRIPTION_ACTIVATED'
    | 'SUBSCRIPTION_EXPIRES'
    | 'SUBSCRIPTION_RENEWAL'
    | 'MESSAGE_RECEIVED'
    | 'OTHER';

export interface NotificationTrackingData {
    title: string;
    message: string;
    category: NotificationCategory;
    action: NotificationAction;
    referenceId?: string;
    referenceType?: string;
    actionUrl?: string;
    metadata?: Record<string, any>;
    priority?: 'low' | 'medium' | 'high';
}

// ─── Notification Tracking Functions ───

/**
 * Create a notification for the current user
 */
export async function trackNotification(data: NotificationTrackingData): Promise<boolean> {
    try {
        const response = await http.post<{ success: boolean }>('/notifications', data);
        return response.data.success;
    } catch (error) {
        console.error('Error tracking notification:', error);
        return false;
    }
}

/**
 * Track appointment booked notification
 */
export async function trackAppointmentBooked(
    appointmentId: string,
    doctorName: string,
    appointmentDate: Date,
    appointmentTime: string
): Promise<boolean> {
    return trackNotification({
        title: 'Appointment Booked',
        message: `Your appointment with ${doctorName} is scheduled for ${new Date(appointmentDate).toLocaleDateString()} at ${appointmentTime}`,
        category: 'APPOINTMENT',
        action: 'APPOINTMENT_BOOKED',
        referenceId: appointmentId,
        referenceType: 'Appointment',
        actionUrl: '/appointments',
        metadata: { doctorName, appointmentDate, appointmentTime },
        priority: 'high'
    });
}

/**
 * Track appointment confirmed notification
 */
export async function trackAppointmentConfirmed(
    appointmentId: string,
    doctorName: string,
    appointmentDate: Date,
    appointmentTime: string
): Promise<boolean> {
    return trackNotification({
        title: 'Appointment Confirmed',
        message: `Your appointment with ${doctorName} on ${new Date(appointmentDate).toLocaleDateString()} at ${appointmentTime} is confirmed`,
        category: 'APPOINTMENT',
        action: 'APPOINTMENT_CONFIRMED',
        referenceId: appointmentId,
        referenceType: 'Appointment',
        actionUrl: '/appointments',
        metadata: { doctorName, appointmentDate, appointmentTime },
        priority: 'high'
    });
}

/**
 * Track appointment cancelled notification
 */
export async function trackAppointmentCancelled(
    appointmentId: string,
    doctorName: string,
    appointmentDate: Date
): Promise<boolean> {
    return trackNotification({
        title: 'Appointment Cancelled',
        message: `Your appointment with ${doctorName} on ${new Date(appointmentDate).toLocaleDateString()} has been cancelled`,
        category: 'APPOINTMENT',
        action: 'APPOINTMENT_CANCELLED',
        referenceId: appointmentId,
        referenceType: 'Appointment',
        actionUrl: '/appointments',
        priority: 'high'
    });
}

/**
 * Track appointment rescheduled notification
 */
export async function trackAppointmentRescheduled(
    appointmentId: string,
    doctorName: string,
    oldDate: Date,
    newDate: Date,
    newTime: string
): Promise<boolean> {
    return trackNotification({
        title: 'Appointment Rescheduled',
        message: `Your appointment with ${doctorName} has been rescheduled from ${new Date(oldDate).toLocaleDateString()} to ${new Date(newDate).toLocaleDateString()} at ${newTime}`,
        category: 'APPOINTMENT',
        action: 'APPOINTMENT_RESCHEDULED',
        referenceId: appointmentId,
        referenceType: 'Appointment',
        actionUrl: '/appointments',
        metadata: { doctorName, oldDate, newDate, newTime },
        priority: 'high'
    });
}

/**
 * Track appointment reminder notification
 */
export async function trackAppointmentReminder(
    appointmentId: string,
    doctorName: string,
    appointmentDate: Date,
    appointmentTime: string
): Promise<boolean> {
    return trackNotification({
        title: 'Appointment Reminder',
        message: `Reminder: Your appointment with ${doctorName} is on ${new Date(appointmentDate).toLocaleDateString()} at ${appointmentTime}`,
        category: 'APPOINTMENT',
        action: 'APPOINTMENT_REMINDER',
        referenceId: appointmentId,
        referenceType: 'Appointment',
        actionUrl: '/appointments',
        priority: 'medium'
    });
}

/**
 * Track prescription issued notification
 */
export async function trackPrescriptionIssued(
    prescriptionId: string,
    doctorName: string,
    medicines: string[]
): Promise<boolean> {
    return trackNotification({
        title: 'New Prescription',
        message: `${doctorName} has issued a new prescription for you`,
        category: 'PRESCRIPTION',
        action: 'PRESCRIPTION_ISSUED',
        referenceId: prescriptionId,
        referenceType: 'Prescription',
        actionUrl: '/prescriptions',
        metadata: { doctorName, medicines },
        priority: 'high'
    });
}

/**
 * Track prescription ready notification
 */
export async function trackPrescriptionReady(
    prescriptionId: string,
    medicines: string[]
): Promise<boolean> {
    return trackNotification({
        title: 'Prescription Ready',
        message: 'Your prescription is ready for pickup',
        category: 'PRESCRIPTION',
        action: 'PRESCRIPTION_READY',
        referenceId: prescriptionId,
        referenceType: 'Prescription',
        actionUrl: '/prescriptions',
        metadata: { medicines },
        priority: 'high'
    });
}

/**
 * Track payment received notification
 */
export async function trackPaymentReceived(
    paymentId: string,
    amount: number,
    currency: string = 'USD'
): Promise<boolean> {
    return trackNotification({
        title: 'Payment Successful',
        message: `Payment of ${currency} ${amount} has been received successfully`,
        category: 'PAYMENT',
        action: 'PAYMENT_RECEIVED',
        referenceId: paymentId,
        referenceType: 'Payment',
        actionUrl: '/payments',
        metadata: { amount, currency },
        priority: 'high'
    });
}

/**
 * Track payment failed notification
 */
export async function trackPaymentFailed(
    paymentId: string,
    amount: number,
    reason?: string
): Promise<boolean> {
    return trackNotification({
        title: 'Payment Failed',
        message: `Payment of ${amount} failed. ${reason ? `Reason: ${reason}` : 'Please try again.'}`,
        category: 'PAYMENT',
        action: 'PAYMENT_FAILED',
        referenceId: paymentId,
        referenceType: 'Payment',
        actionUrl: '/payments',
        metadata: { amount, reason },
        priority: 'high'
    });
}

/**
 * Track subscription activated notification
 */
export async function trackSubscriptionActivated(
    subscriptionId: string,
    planName: string,
    expiryDate?: Date
): Promise<boolean> {
    return trackNotification({
        title: 'Subscription Activated',
        message: `Your ${planName} subscription has been activated`,
        category: 'SUBSCRIPTION',
        action: 'SUBSCRIPTION_ACTIVATED',
        referenceId: subscriptionId,
        referenceType: 'Subscription',
        actionUrl: '/subscription',
        metadata: { planName, expiryDate },
        priority: 'high'
    });
}

/**
 * Track subscription expiring notification
 */
export async function trackSubscriptionExpiring(
    subscriptionId: string,
    planName: string,
    expiryDate: Date
): Promise<boolean> {
    return trackNotification({
        title: 'Subscription Expiring',
        message: `Your ${planName} subscription will expire on ${new Date(expiryDate).toLocaleDateString()}`,
        category: 'SUBSCRIPTION',
        action: 'SUBSCRIPTION_EXPIRES',
        referenceId: subscriptionId,
        referenceType: 'Subscription',
        actionUrl: '/subscription',
        metadata: { planName, expiryDate },
        priority: 'medium'
    });
}

/**
 * Track subscription renewal notification
 */
export async function trackSubscriptionRenewal(
    subscriptionId: string,
    planName: string,
    renewalDate: Date
): Promise<boolean> {
    return trackNotification({
        title: 'Subscription Renewed',
        message: `Your ${planName} subscription has been renewed until ${new Date(renewalDate).toLocaleDateString()}`,
        category: 'SUBSCRIPTION',
        action: 'SUBSCRIPTION_RENEWAL',
        referenceId: subscriptionId,
        referenceType: 'Subscription',
        actionUrl: '/subscription',
        metadata: { planName, renewalDate },
        priority: 'high'
    });
}

/**
 * Track generic system notification
 */
export async function trackSystemNotification(
    title: string,
    message: string,
    actionUrl?: string,
    priority: 'low' | 'medium' | 'high' = 'medium'
): Promise<boolean> {
    return trackNotification({
        title,
        message,
        category: 'SYSTEM',
        action: 'OTHER',
        actionUrl,
        priority
    });
}

/**
 * Get notification tracking history for a specific reference
 */
export async function getNotificationHistory(referenceId: string, referenceType: string) {
    try {
        const response = await http.get<{ data?: unknown }>(`/notifications/history/${referenceId}/${referenceType}`);
        return response.data.data || [];
    } catch (error) {
        console.error('Error fetching notification history:', error);
        return [];
    }
}
