<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\Administration;
use App\Services\User\Contracts\UserServiceInterface;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class SendThankCardTest extends TestCase
{
    use RefreshDatabase;

    private UserServiceInterface $userService;
    private User $sender;
    private User $receiver;

    protected function setUp(): void
    {
        parent::setUp();
        $this->userService = $this->app->make(UserServiceInterface::class);

        // Create sender and receiver
        $this->sender = User::create([
            'msnv'        => 5001,
            'name'        => 'Sender User',
            'mail'        => 'sender@example.com',
            'pass'        => md5('password'),
            'departments' => 1,
            'role'        => config('constants.ROLE_MEMBER'),
            'status'      => config('constants.STATUS_ACTIVE'),
            'card'        => 10,
            'flag_send'   => config('constants.FLAG_SEND_ENABLED'),
            'first_login' => config('constants.FIRST_LOGIN_FALSE'),
        ]);

        $this->receiver = User::create([
            'msnv'        => 5002,
            'name'        => 'Receiver User',
            'mail'        => 'receiver@example.com',
            'pass'        => md5('password'),
            'departments' => 1,
            'role'        => config('constants.ROLE_MEMBER'),
            'status'      => config('constants.STATUS_ACTIVE'),
            'card'        => 0,
            'flag_send'   => config('constants.FLAG_SEND_ENABLED'),
            'first_login' => config('constants.FIRST_LOGIN_FALSE'),
        ]);
    }

    public function test_send_thankcards_reduces_card_balance_and_creates_records(): void
    {
        $this->userService->sendThankcards($this->sender, '5002', 3);

        $this->sender->refresh();
        $this->assertEquals(7, $this->sender->card);

        // Check administration records
        $this->assertDatabaseHas('administration', [
            'msnv'     => 5002,
            'received' => 3,
            'sender'   => 5001,
            'sent'     => 0,
            'receiver' => null,
        ]);

        $this->assertDatabaseHas('administration', [
            'msnv'     => 5001,
            'received' => 0,
            'sender'   => null,
            'sent'     => 3,
            'receiver' => 5002,
        ]);
    }

    public function test_controller_validates_and_stores_thankcard(): void
    {
        $this->actingAs($this->sender);

        $response = $this->postJson(route('user.store_send'), [
            'receiver' => '5002',
            'amount' => 2,
        ]);

        $response->assertStatus(200);
        $response->assertJson(['success' => true]);

        $this->sender->refresh();
        $this->assertEquals(8, $this->sender->card);
    }
}
