<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class AiPromptModel extends BaseModel
{
    protected string $table = 'ai_prompts';
    protected array $fillable = ['feature', 'business_line_id', 'name', 'system_prompt', 'is_active'];
    protected bool $softDeletes = false;
    protected bool $auditStamps = true;

    public function allForFeature(string $feature): array
    {
        $stmt = $this->db->prepare(
            'SELECT p.*, bl.name AS business_line_name FROM ai_prompts p
             LEFT JOIN business_lines bl ON bl.id = p.business_line_id
             WHERE p.feature = :feature ORDER BY p.name'
        );
        $stmt->execute(['feature' => $feature]);

        return $stmt->fetchAll();
    }

    /** The prompt actually used at runtime: the active prompt scoped to this business line, falling back to the active "both brands" prompt. */
    public function activeFor(string $feature, ?int $businessLineId): ?array
    {
        if ($businessLineId !== null) {
            $stmt = $this->db->prepare(
                'SELECT * FROM ai_prompts WHERE feature = :feature AND business_line_id = :bl AND is_active = 1 LIMIT 1'
            );
            $stmt->execute(['feature' => $feature, 'bl' => $businessLineId]);
            $row = $stmt->fetch();
            if ($row !== false) {
                return $row;
            }
        }

        $stmt = $this->db->prepare(
            'SELECT * FROM ai_prompts WHERE feature = :feature AND business_line_id IS NULL AND is_active = 1 LIMIT 1'
        );
        $stmt->execute(['feature' => $feature]);
        $row = $stmt->fetch();

        return $row === false ? null : $row;
    }
}
