<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Listing;
use App\Models\Booking;
use App\Models\Review;
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;

class ReviewsWithImagesSeeder extends Seeder
{
    public function run(): void
    {
        $faker = Faker::create();

        // Step 1: Delete some random reviews to free up user slots
        $this->command->info('Deleting 30 random reviews to free up user slots...');
        $reviewsToDelete = Review::inRandomOrder()->limit(30)->get();
        foreach ($reviewsToDelete as $review) {
            $review->delete();
        }
        $this->command->info('Deleted 30 reviews.');

        // Step 2: Get listings and users
        $listings = Listing::all();
        if ($listings->isEmpty()) {
            $this->command->error('No listings found.');
            return;
        }

        $users = User::where('role', 'user')->get();
        if ($users->isEmpty()) {
            $this->command->error('No users found.');
            return;
        }

        // Step 3: Create 15 reviews with images (1-3 images each)
        $this->command->info('Creating 15 new reviews with images...');

        $comments = [
            'Amazing experience! The place was perfect and exactly as shown in the photos. Highly recommend!',
            'Wonderful stay! Everything was clean and well-maintained. The host was very responsive.',
            'Great location and beautiful property. Loved every moment of our stay here!',
            'Fantastic place! Very comfortable and the amenities were excellent. Will definitely come back!',
            'Perfect getaway! The property exceeded our expectations. Great value for money.',
            'Outstanding service and beautiful surroundings. Could not have asked for a better experience!',
            'Lovely property with amazing views. The host was very accommodating and helpful.',
            'Excellent choice for a relaxing vacation. Everything was top-notch and well-organized.',
            'Superb accommodation! Clean, modern, and in a fantastic location. Highly satisfied!',
            'Incredible experience! The property was beautiful and the host made us feel very welcome.',
            'Best stay ever! Everything was perfect from check-in to check-out. Five stars!',
            'Wonderful property with great amenities. The photos don\'t do it justice - it\'s even better in person!',
            'Amazing place for a family vacation. Spacious, clean, and very comfortable. Loved it!',
            'Perfect in every way! The host thought of everything. Will definitely recommend to friends.',
            'Exceptional experience! Beautiful property and outstanding hospitality. Thank you!',
        ];

        // Sample placeholder image URLs (using public placeholder services)
        $placeholderImages = [
            'https://placehold.co/800x600/4F46E5/FFFFFF/png?text=Review+Photo+1',
            'https://placehold.co/800x600/059669/FFFFFF/png?text=Review+Photo+2',
            'https://placehold.co/800x600/DC2626/FFFFFF/png?text=Review+Photo+3',
            'https://placehold.co/800x600/7C3AED/FFFFFF/png?text=Review+Photo+4',
            'https://placehold.co/800x600/EA580C/FFFFFF/png?text=Review+Photo+5',
            'https://placehold.co/800x600/0891B2/FFFFFF/png?text=Review+Photo+6',
            'https://placehold.co/800x600/DB2777/FFFFFF/png?text=Review+Photo+7',
            'https://placehold.co/800x600/65A30D/FFFFFF/png?text=Review+Photo+8',
        ];

        $reviewsCreated = 0;
        $attempts = 0;
        $maxAttempts = 500; // Increased attempts to handle more conflicts

        while ($reviewsCreated < 15 && $attempts < $maxAttempts) {
            $attempts++;

            $listing = $listings->random();
            $user = $users->random();

            // Check if this user already reviewed this listing
            $existingReview = Review::where('listing_id', $listing->id)
                ->where('user_id', $user->id)
                ->exists();

            if ($existingReview) {
                continue; // Skip if already reviewed
            }

            // Create booking for this review
            $booking = Booking::create([
                'listing_id' => $listing->id,
                'user_id' => $user->id,
                'check_in' => $faker->dateTimeBetween('-6 months', '-1 month'),
                'check_out' => $faker->dateTimeBetween('-1 month', 'now'),
                'guests' => $faker->numberBetween(1, 4),
                'total_price' => $faker->randomFloat(2, 100, 1000),
                'status' => 'completed',
            ]);

            // Randomly decide how many images (1-3)
            $imageCount = $faker->numberBetween(1, 3);
            $reviewImages = [];

            for ($i = 0; $i < $imageCount; $i++) {
                $reviewImages[] = $faker->randomElement($placeholderImages);
            }

            // Create review with images
            Review::create([
                'listing_id' => $listing->id,
                'user_id' => $user->id,
                'booking_id' => $booking->id,
                'rating' => $faker->randomElement([5, 5, 5, 5, 4]), // Mostly 5 stars
                'comment' => $comments[$reviewsCreated % count($comments)],
                'images' => $reviewImages,
                'created_at' => $faker->dateTimeBetween('-3 months', 'now'),
            ]);

            $reviewsCreated++;

            if ($reviewsCreated % 5 == 0) {
                $this->command->info("Created {$reviewsCreated} reviews with images...");
            }
        }

        $this->command->info("Successfully created {$reviewsCreated} reviews with images!");

        // Show summary
        $totalReviews = Review::count();
        $reviewsWithImages = Review::whereNotNull('images')->count();

        $this->command->info("Summary:");
        $this->command->info("  Total reviews: {$totalReviews}");
        $this->command->info("  Reviews with images: {$reviewsWithImages}");
    }
}
