<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class AgentThread extends Model
{
    protected $table = 'agent_threads';

    protected $fillable = [
        'thread_id',
        'admin_id',
        'messages',
        'expires_at',
    ];

    protected $casts = [
        'messages'   => 'array',
        'expires_at' => 'datetime',
    ];

    public static function findOrCreateForAdmin(?string $threadId, int $adminId): static
    {
        if ($threadId) {
            $thread = static::where('thread_id', $threadId)
                            ->where('admin_id', $adminId)
                            ->first();
            if ($thread) {
                return $thread;
            }
        }

        return static::create([
            'thread_id'  => (string) Str::uuid(),
            'admin_id'   => $adminId,
            'messages'   => [],
            'expires_at' => now()->addDays(30),
        ]);
    }
}
