<?php

namespace Modules\WhatsApp\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class WaConversation extends Model
{
    protected $table = 'wa_conversations';

    protected $fillable = [
        'business_id', 'channel_id', 'contact_id', 'wa_id',
        'status', 'labels', 'assigned_user_id', 'ai_enabled',
        'unread_count', 'last_direction', 'last_message_excerpt',
        'last_message_at', 'window_expires_at', 'meta',
    ];

    protected $casts = [
        'ai_enabled'        => 'boolean',
        'unread_count'      => 'integer',
        'labels'            => 'array',
        'last_message_at'   => 'datetime',
        'window_expires_at' => 'datetime',
        'meta'              => 'array',
    ];

    public function messages(): HasMany
    {
        return $this->hasMany(WaMessage::class, 'conversation_id');
    }

    public function channel(): BelongsTo
    {
        return $this->belongsTo(WaChannel::class, 'channel_id');
    }

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

    public function waContact()
    {
        return WaContact::where('business_id', $this->business_id)->where('wa_id', $this->wa_id)->first();
    }

    public function scopeOpen($q)
    {
        return $q->where('status', 'open');
    }

    /** Meta 24h window state (web channels are always free-form). */
    public function isWindowOpen(): bool
    {
        if (!$this->window_expires_at) {
            return false;
        }
        return $this->window_expires_at->isFuture();
    }

    public function displayName(): string
    {
        $contact = $this->waContact();
        return $contact && $contact->name ? $contact->name : $this->wa_id;
    }
}
