<?php

app_require('modules/goals/classes/goals_criteria.php');

use goals\classes\goals_criteria;
use goals\helpers\goals_criteria_target_duration;

it('parses advanced target duration from snake_case fields', function (): void {
    $criteria = goals_criteria::fromJson((string)json_encode([
        'target' => 10,
        'target_duration' => 'WEEKS',
        'target_duration_every' => 2,
    ], JSON_UNESCAPED_UNICODE));

    expect($criteria->target_duration)->toBe(goals_criteria_target_duration::WEEKS);
    expect($criteria->target_duration_every)->toBe(2);

    $payload = $criteria->toArray();
    expect($payload['target_duration'])->toBe('WEEKS');
    expect($payload['target_duration_every'])->toBe(2);
});

it('parses advanced target duration from camelCase aliases', function (): void {
    $criteria = goals_criteria::fromJson((string)json_encode([
        'target' => 10,
        'targetDuration' => 'MONTHS',
        'targetDurationEvery' => 3,
    ], JSON_UNESCAPED_UNICODE));

    expect($criteria->target_duration)->toBe(goals_criteria_target_duration::MONTHS);
    expect($criteria->target_duration_every)->toBe(3);
});

it('normalizes ENTIRE_DURATION to ignore target_duration_every', function (): void {
    $criteria = goals_criteria::fromJson((string)json_encode([
        'target' => 100,
        'target_duration' => 'ENTIRE_DURATION',
        'target_duration_every' => 7,
    ], JSON_UNESCAPED_UNICODE));

    $criteria->validateAndSanitize();

    expect($criteria->target_duration)->toBe(goals_criteria_target_duration::ENTIRE_DURATION);
    expect($criteria->target_duration_every)->toBeNull();
});

it('defaults recurring target_duration_every to 1 when omitted', function (): void {
    $criteria = goals_criteria::fromJson((string)json_encode([
        'target' => 100,
        'target_duration' => 'YEARS',
    ], JSON_UNESCAPED_UNICODE));

    $criteria->validateAndSanitize();

    expect($criteria->target_duration)->toBe(goals_criteria_target_duration::YEARS);
    expect($criteria->target_duration_every)->toBe(1);
});

it('keeps strict legacy mode when target_duration is invalid', function (): void {
    $criteria = goals_criteria::fromJson((string)json_encode([
        'target' => 50,
        'target_duration' => 'invalid-value',
        'target_duration_every' => 4,
    ], JSON_UNESCAPED_UNICODE));

    $criteria->validateAndSanitize();

    expect($criteria->usesAdvancedTargetDuration())->toBeFalse();
    expect($criteria->target_duration)->toBeNull();
    expect($criteria->target_duration_every)->toBeNull();
});
