<?php

declare(strict_types=1);

namespace App\Models;

use App\Dictionary\SendMessage\Type;
use App\Dictionary\WeChat\MiniProgram\SubscribeId;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SendMessageJob extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'relate_order_id',
        'relate_patient_id',
        'type',
        'template_id',
        'scene',
        'content',
        'number',
        'status',
        'fail_reason',
        'sent_at',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'id' => 'integer',
        'relate_order_id' => 'integer',
        'relate_patient_id' => 'integer',
        'number' => 'integer',
        'status' => 'integer',
        'sent_at' => 'datetime',
    ];

    /**
     * Relationships Order.
     */
    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'relate_order_id');
    }

    /**
     * Relationships Patient.
     */
    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class, 'relate_patient_id');
    }

    /**
     * 插入推送消息队列
     * @param int $relate_order_id
     * @param int $relate_patient_id
     * @param Type $type
     * @param SubscribeId|null $template_id
     * @param array $message
     * @param string $scene
     * @return mixed
     */
    public function insertMessageJobs(int $relate_order_id, int $relate_patient_id, Type $type, SubscribeId|null $template_id, array $message, string $scene = ''): mixed
    {
        $data = [
            'relate_order_id'   => $relate_order_id,
            'relate_patient_id' => $relate_patient_id,
            'type' => $type->value,
            'template_id' => $template_id,
            'scene' => '',
            'content' => json_encode($message, JSON_UNESCAPED_UNICODE),
        ];

        return $this->create($data);
    }
}