<?php

use App\Models\System\Settings\OS;
use App\Models\User;

test('newsletter subscription can be created', function () {
    $response = $this->withHeaders(['Api-Token' => config('ecommerce.api.token')])
        ->postJson('/api/v1/forms/newsletter-subscription', [
            'email' => 'test@example.com',
        ]);

    $response->assertStatus(200)
        ->assertJsonStructure([
            'message',
            'data',
        ]);

    $this->assertDatabaseHas('newsletter_users', [
        'email' => 'test@example.com',
    ]);
});

test('newsletter subscription validation fails with invalid email', function () {
    $response = $this->withHeaders(['Api-Token' => config('ecommerce.api.token')])
        ->postJson('/api/v1/forms/newsletter-subscription', [
            'email' => 'invalid-email',
        ]);

    $response->assertStatus(422)
        ->assertJsonValidationErrors(['email']);
});

test('contact us form can be submitted by authenticated user', function () {
    $user = User::factory()->create([
        'password' => 'password',
    ]);

    $payload = [
        'phone' => 61234567,
        'title' => 'Test Title',
        'content' => 'Test Content',
        'type' => OS::MOBILE_APP,
    ];

    $response = $this->actingAs($user, 'sanctum')
        ->withHeaders(['Api-Token' => config('ecommerce.api.token')])
        ->postJson('/api/v1/forms/contact-us', $payload);

    $response->assertStatus(201)
        ->assertJsonStructure([
            'message',
            'data',
        ]);

    $this->assertDatabaseHas('contact_us', [
        'phone' => 61234567,
        'title' => 'Test Title',
        'content' => 'Test Content',
        'type' => OS::MOBILE_APP,
        'user_id' => $user->id,
    ]);
});

test('contact us form submission fails for unauthenticated user', function () {
    $payload = [
        'phone' => 61234567,
        'title' => 'Test Title',
        'content' => 'Test Content',
        'type' => OS::MOBILE_APP,
    ];

    $response = $this->withHeaders(['Api-Token' => config('ecommerce.api.token')])
        ->postJson('/api/v1/forms/contact-us', $payload);

    $response->assertStatus(401);
});

test('contact us form validation fails with invalid data', function () {
    $user = User::factory()->create([
        'password' => 'password',
    ]);

    $response = $this->actingAs($user, 'sanctum')
        ->withHeaders(['Api-Token' => config('ecommerce.api.token')])
        ->postJson('/api/v1/forms/contact-us', [
            'phone' => 'invalid',
            'type' => 'invalid_type',
        ]);

    $response->assertStatus(422)
        ->assertJsonValidationErrors(['phone', 'title', 'content', 'type']);
});
