<?php

namespace Modules\WhatsApp\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class WaContact extends Model
{
    protected $table = 'wa_contacts';

    protected $fillable = [
        'business_id', 'wa_id', 'address_jid', 'name', 'contact_id', 'opted_out',
        'has_whatsapp', 'wa_checked_at', 'last_inbound_at', 'meta',
    ];

    protected $casts = [
        'opted_out'       => 'boolean',
        'has_whatsapp'    => 'boolean',
        'wa_checked_at'   => 'datetime',
        'last_inbound_at' => 'datetime',
        'meta'            => 'array',
    ];

    /**
     * Record whether a number has WhatsApp, learned from a send outcome or an
     * explicit bridge check. Upserts the contact row so it works even for a
     * number we've only ever sent to.
     */
    public static function markWhatsApp(int $businessId, string $waId, bool $available): void
    {
        if (empty($waId) || !Schema::hasTable('wa_contacts') || !Schema::hasColumn('wa_contacts', 'has_whatsapp')) {
            return;
        }

        $contact = static::firstOrNew(['business_id' => $businessId, 'wa_id' => $waId]);
        $contact->has_whatsapp  = $available;
        $contact->wa_checked_at = now();
        $contact->save();
    }

    public static function touchInbound(int $businessId, string $waId, ?string $name = null, ?string $addressJid = null): self
    {
        $contact = static::firstOrNew(['business_id' => $businessId, 'wa_id' => $waId]);
        if ($name && empty($contact->name)) {
            $contact->name = $name;
        }
        // Remember the JID to reply on (e.g. a LID), if the table has the column.
        if ($addressJid && Schema::hasColumn('wa_contacts', 'address_jid')) {
            $contact->address_jid = $addressJid;
        }
        $contact->last_inbound_at = now();
        $contact->save();

        return $contact;
    }
}
