<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\SocialAccount;
use App\Models\SocialAggregate;
use App\Models\Proposal;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class BrandProposalTest extends TestCase
{
    use RefreshDatabase;

    protected $brandAdmin;
    protected $creator;

    protected function setUp(): void
    {
        parent::setUp();

        // Create a brand
        $brand = \App\Models\Brand::factory()->create([
            'name' => 'Test Brand',
        ]);

        // Create a brand admin user
        $this->brandAdmin = User::factory()->create([
            'name' => 'Brand Admin',
            'email' => 'brand@example.com',
            'brand_id' => $brand->id,
        ]);
        $this->brandAdmin->assignRole('brand_admin');

        // Create a creator user
        $this->creator = User::factory()->create([
            'name' => 'Test Creator',
            'email' => 'creator@example.com',
            'influencer_type' => 'Lifestyle',
        ]);
        $this->creator->assignRole('creator');

        // Create social accounts for the creator
        SocialAccount::factory()->create([
            'user_id' => $this->creator->id,
            'provider' => 'youtube',
            'meta' => [
                'username' => 'test_youtube',
                'followers' => 10000,
            ],
        ]);

        SocialAccount::factory()->create([
            'user_id' => $this->creator->id,
            'provider' => 'instagram',
            'meta' => [
                'username' => 'test_instagram',
                'followers' => 5000,
            ],
        ]);

        // Create social aggregates for the creator
        SocialAggregate::factory()->create([
            'user_id' => $this->creator->id,
            'key' => 'total_followers',
            'value' => [
                'value' => 15000,
                'previous' => 14000,
            ],
        ]);

        SocialAggregate::factory()->create([
            'user_id' => $this->creator->id,
            'key' => 'total_posts',
            'value' => [
                'value' => 50,
                'previous' => 45,
            ],
        ]);
    }

    /** @test */
    public function brand_admin_can_view_proposal_create_form()
    {
        $response = $this->actingAs($this->brandAdmin)
            ->get(route('brand.creators.proposal.create', $this->creator));

        $response->assertStatus(200);
        $response->assertSee('Send Proposal to ' . $this->creator->name);
        $response->assertSee('Proposal Title');
        $response->assertSee('Message');
        $response->assertSee('Proposal Type');
    }

    /** @test */
    public function brand_admin_can_submit_valid_proposal()
    {
        Storage::fake('public');

        $response = $this->actingAs($this->brandAdmin)
            ->post(route('brand.creators.proposal.store', $this->creator), [
                'title' => 'Test Collaboration Proposal',
                'message' => 'This is a test proposal message.',
                'type' => 'Collaboration',
                'budget' => 1000.00,
                'duration' => '2 weeks',
                'deliverables' => ['1 Instagram post', '1 YouTube video'],
                'attachment' => UploadedFile::fake()->create('document.pdf', 100),
            ]);

        $response->assertStatus(302);
        $response->assertRedirect(route('brand.creators.show', $this->creator));
        $response->assertSessionHas('success', 'Proposal sent successfully!');

        // Assert that the proposal was created in the database
        $proposal = Proposal::where([
            'brand_id' => $this->brandAdmin->brand_id,
            'creator_id' => $this->creator->id,
            'title' => 'Test Collaboration Proposal',
            'type' => 'Collaboration',
            'status' => 'sent',
        ])->first();

        $this->assertNotNull($proposal);

        // Assert that the attachment was stored
        if ($proposal->attachment_path) {
            Storage::disk('public')->assertExists($proposal->attachment_path);
        }

        // Assert that a notification was sent to the creator
        // Note: We're not testing the notification content here as it's covered in other tests
    }

    /** @test */
    public function proposal_submission_fails_with_invalid_data()
    {
        $response = $this->actingAs($this->brandAdmin)
            ->post(route('brand.creators.proposal.store', $this->creator), [
                'title' => '', // Required field
                'message' => '', // Required field
                'type' => 'Invalid Type', // Not in allowed list
            ]);

        $response->assertStatus(302);
        $response->assertSessionHasErrors(['title', 'message', 'type']);

        // Assert that no proposal was created
        $this->assertDatabaseMissing('proposals', [
            'brand_id' => $this->brandAdmin->brand_id,
            'creator_id' => $this->creator->id,
        ]);
    }

    /** @test */
    public function non_brand_user_cannot_access_proposal_routes()
    {
        $regularUser = User::factory()->create();
        $regularUser->assignRole('user');

        $response = $this->actingAs($regularUser)
            ->get(route('brand.creators.proposal.create', $this->creator));

        $response->assertStatus(403);

        $response = $this->actingAs($regularUser)
            ->post(route('brand.creators.proposal.store', $this->creator), [
                'title' => 'Test Proposal',
                'message' => 'Test message',
                'type' => 'Collaboration',
            ]);

        $response->assertStatus(403);
    }
}