<?php

namespace App\Services;

use App\Models\CustomerNotification;
use App\Models\Order;

class CustomerNotificationService
{
    public function notifyOrderProgress(Order $order, string $progressStatus, ?string $note = null): ?CustomerNotification
    {
        if (! $order->customer_id) {
            return null;
        }

        $title = $this->titleForProgress($progressStatus);
        $body = trim(($note ?: $this->bodyForProgress($order, $progressStatus)));
        $notification = CustomerNotification::query()->create([
            'customer_id' => $order->customer_id,
            'order_id' => $order->id,
            'type' => 'order_progress',
            'title' => $title,
            'body' => $body,
            'url' => route('portal.orders.show', $order),
        ]);

        app(WebPushService::class)->send($notification);

        return $notification;
    }

    private function titleForProgress(string $progressStatus): string
    {
        return match ($progressStatus) {
            'siap_diambil_atau_dikirim' => 'Barang siap diambil/dikirim',
            'sudah_diambil_atau_diterima' => 'Order sudah diterima',
            'sedang_dicuci' => 'Laundry sedang dicuci',
            'sedang_dikeringkan' => 'Laundry sedang dikeringkan',
            'sedang_finishing' => 'Laundry sedang finishing',
            'sedang_dikemas' => 'Laundry sedang dikemas',
            default => 'Update status laundry',
        };
    }

    private function bodyForProgress(Order $order, string $progressStatus): string
    {
        return 'Nota '.$order->invoice_no.' - '.str_replace('_', ' ', $progressStatus).'.';
    }

}
