<?php

use App\Models\MealPosts;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;

uses(RefreshDatabase::class);

it('deletes the authenticated account and related data', function () {
    config()->set('filesystems.default', 's3');

    Storage::fake('s3');

    $user = User::factory()->create([
        'avatar_url' => 'avatars/profile.jpg',
    ]);

    Storage::disk('s3')->put('avatars/profile.jpg', 'avatar');
    Storage::disk('s3')->put('meal-posts/local.jpg', 'meal');

    $localMealPost = MealPosts::factory()->for($user, 'user')->create([
        'image_url' => 'meal-posts/local.jpg',
    ]);
    $remoteMealPost = MealPosts::factory()->for($user, 'user')->create([
        'image_url' => 'https://example.com/meal.jpg',
    ]);
    $deviceToken = $user->deviceTokens()->create([
        'expo_push_token' => 'ExponentPushToken[account-deletion]',
        'platform' => 'ios',
    ]);

    $user->createToken('api');

    DB::table('notifications')->insert([
        'id' => (string) Str::uuid(),
        'type' => 'test',
        'notifiable_type' => User::class,
        'notifiable_id' => $user->getKey(),
        'data' => json_encode(['message' => 'test'], JSON_THROW_ON_ERROR),
        'created_at' => now(),
        'updated_at' => now(),
    ]);
    DB::table('sessions')->insert([
        'id' => 'account-deletion-session',
        'user_id' => $user->getKey(),
        'ip_address' => '127.0.0.1',
        'user_agent' => 'Pest',
        'payload' => 'payload',
        'last_activity' => now()->timestamp,
    ]);
    DB::table('password_reset_tokens')->insert([
        'email' => $user->email,
        'token' => 'reset-token',
        'created_at' => now(),
    ]);

    Sanctum::actingAs($user);

    $this->deleteJson('/api/auth/me')
        ->assertOk()
        ->assertJsonPath('message', __('api.auth.deleted'));

    $this->assertDatabaseMissing('users', ['id' => $user->getKey()]);
    $this->assertDatabaseMissing('meal_posts', ['id' => $localMealPost->getKey()]);
    $this->assertDatabaseMissing('meal_posts', ['id' => $remoteMealPost->getKey()]);
    $this->assertDatabaseMissing('device_tokens', ['id' => $deviceToken->getKey()]);
    $this->assertDatabaseMissing('personal_access_tokens', ['tokenable_id' => $user->getKey()]);
    $this->assertDatabaseMissing('notifications', ['notifiable_id' => $user->getKey()]);
    $this->assertDatabaseMissing('sessions', ['user_id' => $user->getKey()]);
    $this->assertDatabaseMissing('password_reset_tokens', ['email' => $user->email]);

    Storage::disk('s3')->assertMissing('avatars/profile.jpg');
    Storage::disk('s3')->assertMissing('meal-posts/local.jpg');
});

it('requires authentication to delete an account', function () {
    $this->deleteJson('/api/auth/me')
        ->assertUnauthorized();
});
