<?php

namespace Tests\Feature\Api\V1\Email;

use App\Models\User;
use App\Services\Email\EmailDispatchService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Mockery;
use Tests\TestCase;

class EmailControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_senders_endpoint_returns_options(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        putenv('MAIL_SENDERS={"general":{"name":"General","email":"general@example.com"}}');

        $response = $this->getJson('/api/v1/email/senders');

        $response->assertOk();
        $response->assertJsonPath('ok', true);
        $this->assertNotEmpty($response->json('senders'));
    }

    public function test_send_endpoint_uses_dispatch_service(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $mock = Mockery::mock(EmailDispatchService::class);
        $mock->shouldReceive('send')
            ->once()
            ->andReturn(true);

        $this->app->instance(EmailDispatchService::class, $mock);

        $response = $this->postJson('/api/v1/email/send', [
            'recipient' => 'test@example.com',
            'subject' => 'Hello',
            'html_message' => '<p>Test</p>',
            'profile' => 'general',
        ]);

        $response->assertOk();
        $response->assertJsonPath('ok', true);
    }

    private function createUser(): User
    {
        DB::table('users')->insert([
            'id' => 1,
            'school_id' => 1,
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => 'admin@example.com',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'is_verified' => 1,
            'status' => 'Active',
            'is_suspended' => 0,
            'failed_attempts' => 0,
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        return User::query()->findOrFail(1);
    }
}
