<?php

namespace App\Services;

use App\Events\NewNotificationCreated;
use App\Models\AppNotification;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class NotificationService
{
    /**
     * Send a notification to all active users in the given org that hold
     * at least one of the specified Spatie roles.
     *
     * @param  int         $organizationId
     * @param  int|null    $branchId        Scope to a specific branch (or null for org-wide)
     * @param  string[]    $roles           e.g. ['admin', 'manager']
     * @param  string      $type            e.g. 'sale_completed'
     * @param  string      $title
     * @param  string      $body
     * @param  array       $data            Extra JSON payload
     * @param  int|null    $actorId         User who triggered the event (excluded from recipients)
     */
    public static function notifyRoles(
        int $organizationId,
        ?int $branchId,
        array $roles,
        string $type,
        string $title,
        string $body,
        array $data = [],
        ?int $actorId = null
    ): void {
        $recipientIds = User::where('organization_id', $organizationId)
            ->where('is_active', true)
            ->whereHas('roles', fn ($q) => $q->whereIn('name', $roles))
            ->when($actorId, fn ($q) => $q->where('id', '!=', $actorId))
            ->pluck('id');

        if ($recipientIds->isEmpty()) {
            return;
        }

        $now   = now();
        $rows  = $recipientIds->map(fn ($uid) => [
            'organization_id' => $organizationId,
            'branch_id'       => $branchId,
            'user_id'         => $uid,
            'actor_id'        => $actorId,
            'type'            => $type,
            'title'           => $title,
            'body'            => $body,
            'data'            => json_encode($data),
            'read_at'         => null,
            'created_at'      => $now,
            'updated_at'      => $now,
        ])->all();

        DB::table('notifications')->insert($rows);

        // Broadcast real-time notification event so recipients see it instantly
        broadcast(new NewNotificationCreated(
            organizationId: $organizationId,
            type:           $type,
            title:          $title,
            body:           $body,
            data:           $data,
            userId:         null,   // role-based: frontend filters by role
            roles:          $roles,
        ));
    }

    /**
     * Send a notification directly to one specific user.
     */
    public static function notifyUser(
        int $userId,
        int $organizationId,
        ?int $branchId,
        string $type,
        string $title,
        string $body,
        array $data = [],
        ?int $actorId = null
    ): void {
        AppNotification::create([
            'organization_id' => $organizationId,
            'branch_id'       => $branchId,
            'user_id'         => $userId,
            'actor_id'        => $actorId,
            'type'            => $type,
            'title'           => $title,
            'body'            => $body,
            'data'            => $data,
            'read_at'         => null,
        ]);

        // Broadcast real-time notification for this specific user
        broadcast(new NewNotificationCreated(
            organizationId: $organizationId,
            type:           $type,
            title:          $title,
            body:           $body,
            data:           $data,
            userId:         $userId,
            roles:          [],
        ));
    }
}
