<?php

use App\Mail\MissingSongRequest;
use App\Models\ServiceSong;
use App\Models\Song;
use App\Models\SongArrangement;
use App\Models\User;
use App\Services\SongMatchingService;
use Illuminate\Support\Facades\Mail;

/*
|--------------------------------------------------------------------------
| SongMatchingService — Unit-level feature tests
|--------------------------------------------------------------------------
*/

test('autoMatch ordnet Song per CCLI-ID zu', function () {
    $song = Song::factory()->create(['ccli_id' => '7115744', 'has_translation' => true]);
    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => '7115744',
        'song_id' => null,
        'use_translation' => false,
        'matched_at' => null,
    ]);

    $service = app(SongMatchingService::class);
    $result = $service->autoMatch($serviceSong);

    expect($result)->toBeTrue();
    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBe($song->id);
    expect($serviceSong->matched_at)->not->toBeNull();
    expect($serviceSong->use_translation)->toBeTrue();
});

test('autoMatch nutzt CTS-Song-ID als Fallback wenn keine CCLI passt', function () {
    $song = Song::factory()->create([
        'ccli_id' => '7115744',
        'cts_song_id' => 'cts-123',
        'has_translation' => true,
    ]);

    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => '0000000',
        'cts_song_id' => 'cts-123',
        'song_id' => null,
        'use_translation' => false,
        'matched_at' => null,
    ]);

    $service = app(SongMatchingService::class);
    $result = $service->autoMatch($serviceSong);

    expect($result)->toBeTrue();
    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBe($song->id);
    expect($serviceSong->use_translation)->toBeTrue();
});

test('autoMatch gibt false zurück wenn kein CCLI-ID vorhanden', function () {
    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => null,
        'song_id' => null,
        'matched_at' => null,
    ]);

    $service = app(SongMatchingService::class);
    $result = $service->autoMatch($serviceSong);

    expect($result)->toBeFalse();
    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBeNull();
});

test('autoMatch gibt false zurück wenn kein passender Song in DB', function () {
    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => '9999999',
        'song_id' => null,
        'matched_at' => null,
    ]);

    $service = app(SongMatchingService::class);
    $result = $service->autoMatch($serviceSong);

    expect($result)->toBeFalse();
    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBeNull();
});

test('autoMatch überspringt bereits zugeordnete Songs', function () {
    $existingSong = Song::factory()->create(['ccli_id' => '7115744']);

    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => '7115744',
        'song_id' => $existingSong->id,
        'matched_at' => now(),
    ]);

    $service = app(SongMatchingService::class);
    $result = $service->autoMatch($serviceSong);

    expect($result)->toBeFalse();
    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBe($existingSong->id);
});

test('autoMatch setzt song_arrangement_id auf Standard-Arrangement', function () {
    $song = Song::factory()->create(['ccli_id' => '7115744']);
    $defaultArrangement = SongArrangement::factory()->create([
        'song_id' => $song->id,
        'name' => 'normal',
        'is_default' => false,
    ]);

    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => '7115744',
        'song_id' => null,
        'song_arrangement_id' => null,
    ]);

    $service = app(SongMatchingService::class);
    $result = $service->autoMatch($serviceSong);

    expect($result)->toBeTrue();
    $serviceSong->refresh();
    expect($serviceSong->song_arrangement_id)->toBe($defaultArrangement->id);
});

test('autoMatch bevorzugt is_default=true Arrangement', function () {
    $song = Song::factory()->create(['ccli_id' => '7115744']);
    $normalArrangement = SongArrangement::factory()->create([
        'song_id' => $song->id,
        'name' => 'normal',
        'is_default' => false,
    ]);
    $defaultArrangement = SongArrangement::factory()->create([
        'song_id' => $song->id,
        'name' => 'Standard',
        'is_default' => true,
    ]);

    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => '7115744',
        'song_id' => null,
        'song_arrangement_id' => null,
    ]);

    $service = app(SongMatchingService::class);
    $service->autoMatch($serviceSong);

    $serviceSong->refresh();
    expect($serviceSong->song_arrangement_id)->toBe($defaultArrangement->id);
});

test('autoMatch nutzt erstes Arrangement wenn kein Standard vorhanden', function () {
    $song = Song::factory()->create(['ccli_id' => '7115744']);
    $firstArrangement = SongArrangement::factory()->create([
        'song_id' => $song->id,
        'name' => 'Erste',
        'is_default' => false,
    ]);
    SongArrangement::factory()->create([
        'song_id' => $song->id,
        'name' => 'Zweite',
        'is_default' => false,
    ]);

    $serviceSong = ServiceSong::factory()->create([
        'cts_ccli_id' => '7115744',
        'song_id' => null,
        'song_arrangement_id' => null,
    ]);

    $service = app(SongMatchingService::class);
    $service->autoMatch($serviceSong);

    $serviceSong->refresh();
    expect($serviceSong->song_arrangement_id)->toBe($firstArrangement->id);
});

test('manualAssign ordnet Song manuell zu', function () {
    $song = Song::factory()->create(['has_translation' => true]);
    $serviceSong = ServiceSong::factory()->create([
        'song_id' => null,
        'use_translation' => false,
        'matched_at' => null,
    ]);

    $service = app(SongMatchingService::class);
    $service->manualAssign($serviceSong, $song);

    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBe($song->id);
    expect($serviceSong->matched_at)->not->toBeNull();
    expect($serviceSong->use_translation)->toBeTrue();
});

test('manualAssign überschreibt bestehende Zuordnung', function () {
    $oldSong = Song::factory()->create();
    $newSong = Song::factory()->create();

    $serviceSong = ServiceSong::factory()->create([
        'song_id' => $oldSong->id,
        'matched_at' => now()->subDay(),
    ]);

    $service = app(SongMatchingService::class);
    $service->manualAssign($serviceSong, $newSong);

    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBe($newSong->id);
    expect($serviceSong->matched_at)->not->toBeNull();
});

test('manualAssign setzt song_arrangement_id wenn null', function () {
    $song = Song::factory()->create();
    $arrangement = SongArrangement::factory()->create([
        'song_id' => $song->id,
        'name' => 'normal',
    ]);

    $serviceSong = ServiceSong::factory()->create([
        'song_id' => null,
        'song_arrangement_id' => null,
    ]);

    $service = app(SongMatchingService::class);
    $service->manualAssign($serviceSong, $song);

    $serviceSong->refresh();
    expect($serviceSong->song_arrangement_id)->toBe($arrangement->id);
});

test('manualAssign behält bestehende song_arrangement_id bei', function () {
    $oldSong = Song::factory()->create();
    $oldArrangement = SongArrangement::factory()->create([
        'song_id' => $oldSong->id,
        'name' => 'old',
    ]);

    $newSong = Song::factory()->create();
    $newArrangement = SongArrangement::factory()->create([
        'song_id' => $newSong->id,
        'name' => 'new',
    ]);

    $serviceSong = ServiceSong::factory()->create([
        'song_id' => $oldSong->id,
        'song_arrangement_id' => $oldArrangement->id,
    ]);

    $service = app(SongMatchingService::class);
    $service->manualAssign($serviceSong, $newSong);

    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBe($newSong->id);
    expect($serviceSong->song_arrangement_id)->toBe($oldArrangement->id);
});

test('requestCreation sendet E-Mail und setzt request_sent_at', function () {
    Mail::fake();

    $serviceSong = ServiceSong::factory()->create([
        'cts_song_name' => 'Großer Gott',
        'cts_ccli_id' => '12345678',
        'request_sent_at' => null,
    ]);

    $service = app(SongMatchingService::class);
    $service->requestCreation($serviceSong);

    Mail::assertSent(MissingSongRequest::class, function (MissingSongRequest $mail) {
        return $mail->songName === 'Großer Gott'
            && $mail->ccliId === '12345678';
    });

    $serviceSong->refresh();
    expect($serviceSong->request_sent_at)->not->toBeNull();
});

test('unassign entfernt Zuordnung', function () {
    $song = Song::factory()->create();
    $serviceSong = ServiceSong::factory()->create([
        'song_id' => $song->id,
        'matched_at' => now(),
    ]);

    $service = app(SongMatchingService::class);
    $service->unassign($serviceSong);

    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBeNull();
    expect($serviceSong->matched_at)->toBeNull();
});

/*
|--------------------------------------------------------------------------
| ServiceSongController — API endpoint tests
|--------------------------------------------------------------------------
*/

test('POST /api/service-songs/{id}/assign ordnet Song zu', function () {
    $user = User::factory()->create();
    $song = Song::factory()->create();
    $serviceSong = ServiceSong::factory()->create([
        'song_id' => null,
        'matched_at' => null,
    ]);

    $response = $this->actingAs($user)
        ->postJson("/api/service-songs/{$serviceSong->id}/assign", [
            'song_id' => $song->id,
        ]);

    $response->assertOk()
        ->assertJson(['message' => 'Song erfolgreich zugeordnet']);

    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBe($song->id);
});

test('POST /api/service-songs/{id}/assign validiert song_id', function () {
    $user = User::factory()->create();
    $serviceSong = ServiceSong::factory()->create([
        'song_id' => null,
    ]);

    $response = $this->actingAs($user)
        ->postJson("/api/service-songs/{$serviceSong->id}/assign", [
            'song_id' => 99999,
        ]);

    $response->assertUnprocessable();
});

test('POST /api/service-songs/{id}/request sendet Anfrage-E-Mail', function () {
    Mail::fake();

    $user = User::factory()->create();
    $serviceSong = ServiceSong::factory()->create([
        'cts_song_name' => 'Way Maker',
        'cts_ccli_id' => '7115744',
        'request_sent_at' => null,
    ]);

    $response = $this->actingAs($user)
        ->postJson("/api/service-songs/{$serviceSong->id}/request");

    $response->assertOk()
        ->assertJson(['message' => 'Anfrage wurde gesendet']);

    Mail::assertSent(MissingSongRequest::class);

    $serviceSong->refresh();
    expect($serviceSong->request_sent_at)->not->toBeNull();
});

test('POST /api/service-songs/{id}/unassign entfernt Zuordnung', function () {
    $user = User::factory()->create();
    $song = Song::factory()->create();
    $serviceSong = ServiceSong::factory()->create([
        'song_id' => $song->id,
        'matched_at' => now(),
    ]);

    $response = $this->actingAs($user)
        ->postJson("/api/service-songs/{$serviceSong->id}/unassign");

    $response->assertOk()
        ->assertJson(['message' => 'Zuordnung entfernt']);

    $serviceSong->refresh();
    expect($serviceSong->song_id)->toBeNull();
    expect($serviceSong->matched_at)->toBeNull();
});

test('API Endpunkte erfordern Authentifizierung', function () {
    $serviceSong = ServiceSong::factory()->create();

    $this->postJson("/api/service-songs/{$serviceSong->id}/assign", ['song_id' => 1])
        ->assertUnauthorized();

    $this->postJson("/api/service-songs/{$serviceSong->id}/request")
        ->assertUnauthorized();

    $this->postJson("/api/service-songs/{$serviceSong->id}/unassign")
        ->assertUnauthorized();
});

test('API gibt 404 für nicht existierende ServiceSong', function () {
    $user = User::factory()->create();
    $song = Song::factory()->create();

    $this->actingAs($user)
        ->postJson('/api/service-songs/99999/assign', ['song_id' => $song->id])
        ->assertNotFound();
});
