<?php

namespace App\Domain\WhatsApp\Models;

use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\WhatsApp\Enums\MessageStatus;
use App\Domain\WhatsApp\Enums\MessageType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Domain\Shared\Traits\BelongsToBranch;

class WhatsAppMessage extends Model
{
    use BelongsToAcademy, BelongsToBranch;

    /**
     * branch_id NULL means every branch uses this row — catalogue and
     * configuration, not an operational record owned by one branch.
     */
    protected static bool $branchScopeAllowsShared = true;

    protected $table = 'whatsapp_messages';

    protected $fillable = [
        'academy_id', 'branch_id',
        'wa_message_id',
        'phone_number',
        'type',
        'content',
        'status',
        'error_message',
        'payload',
        'response',
        'sent_by',
        'sent_at',
        'delivered_at',
        'read_at',
    ];

    protected function casts(): array
    {
        return [
            'type' => MessageType::class,
            'status' => MessageStatus::class,
            'payload' => 'array',
            'response' => 'array',
            'sent_at' => 'datetime',
            'delivered_at' => 'datetime',
            'read_at' => 'datetime',
        ];
    }

    public function sender(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'sent_by');
    }
}
