<?php

namespace App\Models;

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

class WhatsAppConversation extends Model
{
    /** Laravel infiere `whats_app_conversations`; la migración crea `whatsapp_conversations`. */
    protected $table = 'whatsapp_conversations';

    protected $fillable = [
        'phone',
        'state',
        'data',
        'human_takeover',
        'human_takeover_at',
        'human_takeover_by',
        'last_message_at',
    ];

    protected $casts = [
        'data' => \App\Casts\SafeJsonArray::class,
        'human_takeover' => 'boolean',
        'human_takeover_at' => 'datetime',
        'last_message_at' => 'datetime',
    ];

    public function takeoverUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'human_takeover_by');
    }

    public static function getOrCreate(string $phone): self
    {
        return self::firstOrCreate(
            ['phone' => preg_replace('/[^0-9]/', '', $phone)],
            ['state' => 'menu', 'data' => []]
        );
    }

    public function setState(string $state, array $data = []): void
    {
        $this->update([
            'state' => $state,
            'data' => array_merge($this->data ?? [], $data),
        ]);
    }

    public function reset(): void
    {
        $this->update(['state' => 'menu', 'data' => []]);
    }

    public function enableHumanTakeover(?int $userId = null): void
    {
        $this->update([
            'human_takeover' => true,
            'human_takeover_at' => now(),
            'human_takeover_by' => $userId,
        ]);
    }

    public function releaseHumanTakeover(): void
    {
        $this->update([
            'human_takeover' => false,
            'human_takeover_at' => null,
            'human_takeover_by' => null,
        ]);
        $this->reset();
    }
}
