<?php

namespace Tests\Unit\B2B;

use Mtc\Modules\B2B\Models\TradeCustomer;
use Mtc\Modules\B2B\Models\TradeTier;
use Mtc\Modules\Members\Models\Member;
use Tests\TestCase;

class TradeTierDeletionTest extends TestCase
{

    public function test_tier_with_no_customers_can_be_deleted()
    {
        $tier = TradeTier::create([
            'name' => 'Empty Tier',
            'discount_percentage' => 5,
            'sort_order' => 1,
        ]);

        $tierId = $tier->id;
        $tier->delete();

        $this->assertNull(TradeTier::find($tierId));
    }

    public function test_tier_with_customers_count_is_accurate()
    {
        $tier = TradeTier::create([
            'name' => 'Bronze',
            'discount_percentage' => 5,
            'sort_order' => 1,
        ]);

        $member1 = new Member();
        $member1->email = 'test1-' . uniqid() . '@example.com';
        $member1->save();

        $member2 = new Member();
        $member2->email = 'test2-' . uniqid() . '@example.com';
        $member2->save();

        TradeCustomer::create([
            'member_id' => $member1->id,
            'tier_id' => $tier->id,
            'company_name' => 'Company A',
            'phone' => '07700900001',
            'status' => 'approved',
        ]);

        TradeCustomer::create([
            'member_id' => $member2->id,
            'tier_id' => $tier->id,
            'company_name' => 'Company B',
            'phone' => '07700900002',
            'status' => 'approved',
        ]);

        $tier = TradeTier::withCount('customers')->find($tier->id);
        $this->assertEquals(2, $tier->customers_count);
    }

    public function test_tier_deletion_blocked_when_customers_assigned()
    {
        $tier = TradeTier::create([
            'name' => 'Bronze',
            'discount_percentage' => 5,
            'sort_order' => 1,
        ]);

        $member = new Member();
        $member->email = 'test-' . uniqid() . '@example.com';
        $member->save();

        TradeCustomer::create([
            'member_id' => $member->id,
            'tier_id' => $tier->id,
            'company_name' => 'Test Co',
            'phone' => '07700900000',
            'status' => 'approved',
        ]);

        $this->expectException(\RuntimeException::class);
        $tier->delete();
    }
}
