<?php

use App\Enums\MealPostVisibility;
use App\Models\MealPosts;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;

uses(RefreshDatabase::class);

it('stores and returns the selected meal post visibility', function () {
    $user = User::factory()->create();

    Sanctum::actingAs($user);

    $response = $this->postJson('/api/meal-posts', [
        'image_url' => 'https://example.com/meal.jpg',
        'title' => 'Bowl saumon avocat',
        'eaten_at' => '2026-05-16T12:00:00.000Z',
        'visibility' => MealPostVisibility::Followers->value,
        'type' => \App\Enums\MealPostType::BREAKFAST->value,
    ]);

    $response
        ->assertCreated()
        ->assertJsonPath('data.visibility', MealPostVisibility::Followers->value);

    $this->assertDatabaseHas('meal_posts', [
        'id' => $response->json('data.id'),
        'user_id' => $user->id,
        'visibility' => MealPostVisibility::Followers->value,
    ]);
});

it('defaults meal post visibility to private', function () {
    $user = User::factory()->create();

    Sanctum::actingAs($user);

    $response = $this->postJson('/api/meal-posts', [
        'image_url' => 'https://example.com/meal.jpg',
        'title' => 'Bowl saumon avocat',
        'eaten_at' => '2026-05-16T12:00:00.000Z',
        'type' => \App\Enums\MealPostType::BREAKFAST->value,
    ]);

    $response
        ->assertCreated()
        ->assertJsonPath('data.visibility', MealPostVisibility::Private->value);
});

it('validates meal post visibility', function () {
    Sanctum::actingAs(User::factory()->create());

    $response = $this->postJson('/api/meal-posts', [
        'image_url' => 'https://example.com/meal.jpg',
        'title' => 'Bowl saumon avocat',
        'eaten_at' => '2026-05-16T12:00:00.000Z',
        'visibility' => 'friends',
        'type' => \App\Enums\MealPostType::BREAKFAST->value,
    ]);

    $response
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['visibility']);
});

it('patches meal post visibility without requiring creation fields', function () {
    $user = User::factory()->create();
    $mealPost = MealPosts::factory()->for($user, 'user')->create([
        'visibility' => MealPostVisibility::Private,
    ]);

    Sanctum::actingAs($user);

    $response = $this->patchJson("/api/meal-posts/{$mealPost->id}", [
        'visibility' => MealPostVisibility::Public->value,
    ]);

    $response
        ->assertOk()
        ->assertJsonPath('data.visibility', MealPostVisibility::Public->value);

    $this->assertDatabaseHas('meal_posts', [
        'id' => $mealPost->id,
        'visibility' => MealPostVisibility::Public->value,
    ]);
});
