<?php

declare(strict_types=1);

namespace ImovelZapAi\Publishing\Infrastructure\Persistence\Eloquent;

use Database\Factories\TenantFeedGenerationLogFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\BelongsToTenant;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\HasUuidPrimaryKey;

class TenantFeedGenerationLogModel extends Model
{
    use BelongsToTenant;

    /** @use HasFactory<TenantFeedGenerationLogFactory> */
    use HasFactory;
    use HasUuidPrimaryKey;

    public $timestamps = false;

    protected $table = 'tenant_feed_generation_logs';

    /** @var list<string> */
    protected $fillable = [
        'tenant_id',
        'version',
        'listing_count',
        'content_hash',
        'duration_ms',
        'success',
        'errors',
        'created_at',
    ];

    /** @return array<string, string> */
    protected function casts(): array
    {
        return [
            'listing_count' => 'integer',
            'duration_ms' => 'integer',
            'success' => 'boolean',
            'created_at' => 'datetime',
        ];
    }

    /** @return list<string> */
    public function errorList(): array
    {
        if ($this->errors === null || trim((string) $this->errors) === '') {
            return [];
        }

        $decoded = json_decode((string) $this->errors, true);

        if (is_array($decoded)) {
            return array_values(array_filter(array_map('strval', $decoded)));
        }

        return [trim((string) $this->errors)];
    }

    protected static function newFactory(): TenantFeedGenerationLogFactory
    {
        return TenantFeedGenerationLogFactory::new();
    }
}
