<?php

namespace Kylin\Pet\Services;

use App\Models\Vaccination;
use App\Models\Deworming;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Support\Facades\Notification;

/**
 * 健康提醒服务
 * 疫苗到期提醒（GB/T 43825-2024）、驱虫到期提醒、库存预警
 */
class HealthReminderService
{
    /**
     * 获取即将到期的疫苗提醒
     */
    public function getVaccinationReminders(int $days = 7): array
    {
        $targetDate = Carbon::now()->addDays($days);

        return Vaccination::with(['pet'])
            ->where('next_vaccination_at', '<=', $targetDate)
            ->where('next_vaccination_at', '>=', Carbon::now())
            ->get()
            ->map(fn($v) => [
                'pet_name' => $v->pet?->name,
                'vaccine_name' => $v->vaccine_name,
                'next_vaccination_at' => $v->next_vaccination_at?->toDateString(),
                'days_until' => Carbon::now()->diffInDays($v->next_vaccination_at, false),
            ])
            ->toArray();
    }

    /**
     * 获取即将到期的驱虫提醒
     */
    public function getDewormingReminders(int $days = 7): array
    {
        $targetDate = Carbon::now()->addDays($days);

        return Deworming::with(['pet'])
            ->where('next_deworming_at', '<=', $targetDate)
            ->where('next_deworming_at', '>=', Carbon::now())
            ->get()
            ->map(fn($d) => [
                'pet_name' => $d->pet?->name,
                'deworming_name' => $d->deworming_name,
                'next_deworming_at' => $d->next_deworming_at?->toDateString(),
                'days_until' => Carbon::now()->diffInDays($d->next_deworming_at, false),
            ])
            ->toArray();
    }

    /**
     * 获取库存预警商品
     */
    public function getStockWarnings(): array
    {
        return Product::whereColumn('stock', '<=', 'stock_warning')
            ->where('status', 1)
            ->get()
            ->map(fn($p) => [
                'name' => $p->name,
                'stock' => $p->stock,
                'stock_warning' => $p->stock_warning,
            ])
            ->toArray();
    }
}
