<?php

namespace Tests\Tenant;

use App\Master\Models\VehicleMake;
use Mtc\MercuryDataModels\CatalogOffer;
use Mtc\MercuryDataModels\CatalogOfferRule;
use Tests\TenantTestCase;

class CatalogOfferRuleTest extends TenantTestCase
{
    public function testRuleBelongsToCatalogOffer()
    {
        $offer = CatalogOffer::factory()->create();
        $rule = CatalogOfferRule::query()->create([
            'catalog_offer_id' => $offer->id,
            'field' => 'make_id',
            'condition' => '=',
            'value' => '123',
        ]);

        $this->assertEquals($offer->id, $rule->catalogOffer->id);
    }

    public function testCatalogOfferHasManyRules()
    {
        $offer = CatalogOffer::factory()->create();
        CatalogOfferRule::query()->create([
            'catalog_offer_id' => $offer->id,
            'field' => 'make_id',
            'condition' => '=',
            'value' => '123',
        ]);
        CatalogOfferRule::query()->create([
            'catalog_offer_id' => $offer->id,
            'field' => 'price',
            'condition' => '>',
            'value' => '10000',
        ]);

        $this->assertCount(2, $offer->rules);
    }

    public function testFieldNameAttribute()
    {
        $rule = new CatalogOfferRule([
            'field' => 'make_id',
            'condition' => '=',
            'value' => '123',
        ]);

        $this->assertNotNull($rule->field_name);
        $this->assertIsString($rule->field_name);
    }

    public function testConditionNameAttribute()
    {
        $rule = new CatalogOfferRule([
            'field' => 'make_id',
            'condition' => '=',
            'value' => '123',
        ]);

        $this->assertNotNull($rule->condition_name);
        $this->assertIsString($rule->condition_name);
    }

    public function testValueNameAttributeWithRelatedModel()
    {
        $make = VehicleMake::factory()->create(['name' => 'Test Make']);

        $rule = new CatalogOfferRule([
            'field' => 'make_id',
            'condition' => '=',
            'value' => $make->id,
        ]);

        $this->assertEquals('Test Make', $rule->value_name);
    }

    public function testValueNameAttributeWithPlainValue()
    {
        $rule = new CatalogOfferRule([
            'field' => 'price',
            'condition' => '>',
            'value' => '10000',
        ]);

        $this->assertEquals('10000', $rule->value_name);
    }

    public function testRuleAppendsAttributes()
    {
        $offer = CatalogOffer::factory()->create();
        $rule = CatalogOfferRule::query()->create([
            'catalog_offer_id' => $offer->id,
            'field' => 'price',
            'condition' => '>',
            'value' => '5000',
        ]);

        $array = $rule->toArray();

        $this->assertArrayHasKey('field_name', $array);
        $this->assertArrayHasKey('condition_name', $array);
        $this->assertArrayHasKey('value_name', $array);
    }
}
