<?php

namespace App\Models;

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

class ManyChatIntegracion extends Model
{
    protected $table = 'manychat_integraciones';

    protected $fillable = [
        'empresa_id',
        'api_token',
        'activo',
        'nombre_integracion',
        'template_producto',
        'template_productos_multiples',
        'template_no_encontrado',
        'webhook_url',
        'ultima_conexion',
    ];

    protected $hidden = ['api_token'];

    protected function casts(): array
    {
        return [
            'activo' => 'boolean',
            'ultima_conexion' => 'datetime',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    public function empresa(): BelongsTo
    {
        return $this->belongsTo(Empresa::class, 'empresa_id');
    }

    public function logs(): HasMany
    {
        return $this->hasMany(ManyChatLog::class, 'empresa_id', 'empresa_id');
    }

    public static function generateToken(): string
    {
        return Str::random(64);
    }

    public static function findByToken(string $token): ?self
    {
        return self::query()->where('api_token', $token)->first();
    }

    public function touchConexion(): void
    {
        $this->timestamps = false;
        $this->ultima_conexion = now();
        $this->save();
        $this->timestamps = true;
    }
}
