<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class AudienceSegmentModel extends BaseModel
{
    protected string $table = 'audience_segments';
    protected array $fillable = ['name', 'description', 'filter_definition'];
    protected bool $softDeletes = true;
    protected bool $auditStamps = false;

    public function create(string $name, ?string $description, array $filterDefinition, int $userId): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO audience_segments (name, description, filter_definition, created_by, created_at, updated_at)
             VALUES (:name, :description, :filter, :user, NOW(), NOW())'
        );
        $stmt->execute([
            'name' => $name,
            'description' => $description,
            'filter' => json_encode($filterDefinition),
            'user' => $userId,
        ]);

        return (int) $this->db->lastInsertId();
    }

    public function allActive(): array
    {
        return $this->db->query('SELECT * FROM audience_segments WHERE deleted_at IS NULL ORDER BY name')->fetchAll();
    }
}
