<?php

namespace App\Helpers;

use App\Models\Notification;
use Illuminate\Support\Str;
use Illuminate\Database\QueryException;
use Symfony\Component\HttpFoundation\Response;
use App\Helpers\ApiResponse;
use Exception;

class NotificationHelper
{
    /**
     * Create a new notification with safe exception handling
     */
    public static function send(
        string $type,
        string $message,
        array $data = [],
        ?string $franchiseeId = null,
        string $senderId,
        string $receiverId,
        string $status = 'Pending',
        array|string|null $globalNotification = null,
    ) {
        try {
            $notification = Notification::create([
                'id' => (string) Str::uuid(),
                'franchisee_id' => $franchiseeId, // null = admin
                'sender_id' => $senderId,
                'receiver_id' => $receiverId,
                'type' => $type,
                'message' => $message,
                'data' => $data,
                'status' => $status,
                'global_notification' => is_array($globalNotification)
                    ? $globalNotification
                    : json_decode($globalNotification, true),
            ]);

            return ApiResponse::success(
                $notification,
                'Notification created successfully',
                Response::HTTP_CREATED
            );

        } catch (QueryException $e) {
            // Handles database-specific errors
            return ApiResponse::error(
                'Database error: ' . $e->getMessage(),
                Response::HTTP_BAD_REQUEST
            );
        } catch (Exception $e) {
            // Handles general exceptions
            return ApiResponse::error(
                'Unexpected error: ' . $e->getMessage(),
                Response::HTTP_INTERNAL_SERVER_ERROR
            );
        }
    }
}
