<?php
require_once __DIR__ . '/../Core.php';

class MailRule extends Model
{
    private const FIELDS = ['from_address', 'subject', 'body'];
    private const OPERATORS = ['contains', 'equals'];

    public function all(): array
    {
        return $this->db->query('SELECT * FROM mail_rules ORDER BY sort_order ASC, created_at DESC')->fetchAll();
    }

    public function active(): array
    {
        return $this->db->query('SELECT * FROM mail_rules WHERE is_active = 1 ORDER BY sort_order ASC, created_at DESC')->fetchAll();
    }

    public function create(array $data): array
    {
        $name = trim((string)($data['name'] ?? ''));
        $matchValue = trim((string)($data['match_value'] ?? ''));
        if ($name === '' || $matchValue === '') {
            throw new RuntimeException('Rule name and match value are required.');
        }
        $field = $this->normalizeField((string)($data['match_field'] ?? 'from_address'));
        $operator = $this->normalizeOperator((string)($data['match_operator'] ?? 'contains'));
        $stmt = $this->db->prepare('INSERT INTO mail_rules (name, match_field, match_operator, match_value, target_folder_key, target_bucket, target_label_key, is_active, sort_order, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $name,
            $field,
            $operator,
            $matchValue,
            trim((string)($data['target_folder_key'] ?? '')) ?: null,
            trim((string)($data['target_bucket'] ?? '')) ?: null,
            trim((string)($data['target_label_key'] ?? '')) ?: null,
            !empty($data['is_active']) ? 1 : 0,
            (int)($data['sort_order'] ?? 100),
            (int)(current_user()['id'] ?? 0) ?: null,
        ]);
        return ['name' => $name, 'match_field' => $field, 'match_operator' => $operator, 'match_value' => $matchValue];
    }

    public function match(array $rule, array $message): bool
    {
        $field = $this->normalizeField((string)($rule['match_field'] ?? 'from_address'));
        $operator = $this->normalizeOperator((string)($rule['match_operator'] ?? 'contains'));
        $needle = strtolower(trim((string)($rule['match_value'] ?? '')));
        if ($needle === '') {
            return false;
        }
        $haystack = strtolower(trim((string)($message[$field] ?? '')));
        if ($haystack === '') {
            return false;
        }
        if ($operator === 'equals') {
            return $haystack === $needle;
        }
        return str_contains($haystack, $needle);
    }

    public function normalizeField(string $field): string
    {
        $field = strtolower(trim($field));
        return in_array($field, self::FIELDS, true) ? $field : 'from_address';
    }

    public function normalizeOperator(string $operator): string
    {
        $operator = strtolower(trim($operator));
        return in_array($operator, self::OPERATORS, true) ? $operator : 'contains';
    }
}
