<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * Lead captured by the public-facing AI agent on the homepage. Each row is
 * one visitor conversation — the chat transcript lives inline in the
 * `transcript` JSON column to keep the schema flat and the admin queries
 * cheap. Not tied to a Workspace; surfaced only in the admin console.
 */
class HomepageLead extends Model
{
    use HasFactory;

    public const STATUS_NEW       = 'new';
    public const STATUS_CONTACTED = 'contacted';
    public const STATUS_QUALIFIED = 'qualified';
    public const STATUS_CLOSED    = 'closed';
    public const STATUS_SPAM      = 'spam';

    public const STATUSES = [
        self::STATUS_NEW,
        self::STATUS_CONTACTED,
        self::STATUS_QUALIFIED,
        self::STATUS_CLOSED,
        self::STATUS_SPAM,
    ];

    protected $fillable = [
        'session_id',
        'name',
        'email',
        'company',
        'use_case',
        'page_url',
        'ip_address',
        'user_agent',
        'transcript',
        'status',
        'admin_notes',
        'ai_provider',
        'ai_model',
        'ai_tokens_in',
        'ai_tokens_out',
        'ai_total_cost',
        'message_count',
        'last_message_at',
    ];

    protected function casts(): array
    {
        return [
            'transcript'      => 'array',
            'ai_total_cost'   => 'decimal:6',
            'ai_tokens_in'    => 'integer',
            'ai_tokens_out'   => 'integer',
            'message_count'   => 'integer',
            'last_message_at' => 'datetime',
        ];
    }

    public function appendMessage(string $role, string $content): void
    {
        $transcript = $this->transcript ?? [];
        $transcript[] = [
            'role'    => $role,
            'content' => $content,
            'at'      => now()->toIso8601String(),
        ];

        $this->transcript = $transcript;
        $this->message_count = count($transcript);
        $this->last_message_at = now();
    }

    public function scopeStatus(Builder $q, string $status): Builder
    {
        return $q->where('status', $status);
    }

    public function scopeSearch(Builder $q, ?string $term): Builder
    {
        if (! $term) return $q;
        return $q->where(function (Builder $w) use ($term) {
            $like = '%'.$term.'%';
            $w->where('name', 'like', $like)
              ->orWhere('email', 'like', $like)
              ->orWhere('company', 'like', $like);
        });
    }

    public function getDisplayNameAttribute(): string
    {
        return $this->name ?: ($this->email ?: 'Anonymous visitor');
    }

    public function getFirstMessageAttribute(): ?string
    {
        $transcript = $this->transcript ?? [];
        foreach ($transcript as $entry) {
            if (($entry['role'] ?? null) === 'user' && ! empty($entry['content'])) {
                return $entry['content'];
            }
        }
        return null;
    }
}
