<?php

use App\Models\User;
use App\Models\ChatMessage;
use App\Models\Ad;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

// 1. Get Main Test User
$mainUser = User::where('email', 'test@clxpro.com')->first();
if (!$mainUser) {
    echo "Main test user not found. Please run create_test_user.php first.\n";
    exit;
}

// 2. Create/Get Second User (Buyer)
$buyerEmail = 'buyer@clxpro.com';
$buyer = User::where('email', $buyerEmail)->first();
if (!$buyer) {
    $buyer = User::create([
        'name' => 'Alice Buyer',
        'email' => $buyerEmail,
        'password' => Hash::make('password123'),
        'role' => 'user',
    ]);
    echo "Created buyer: $buyerEmail\n";
} else {
    echo "Buyer exists: $buyerEmail\n";
}

// 3. Create a Message from Buyer to Main User (to show in Main User's inbox)
// Link to one of Main User's ads if possible
$ad = Ad::where('user_id', $mainUser->id)->first();
$adId = $ad ? $ad->id : null;

// Clear existing chats between them for clean slate
ChatMessage::where(function($q) use ($mainUser, $buyer) {
    $q->where('sender_id', $mainUser->id)->where('receiver_id', $buyer->id);
})->orWhere(function($q) use ($mainUser, $buyer) {
    $q->where('sender_id', $buyer->id)->where('receiver_id', $mainUser->id);
})->delete();

// Message 1: From Buyer
ChatMessage::create([
    'sender_id' => $buyer->id,
    'receiver_id' => $mainUser->id,
    'message' => 'Hi, is this item still available?',
    'ad_id' => $adId,
    'created_at' => now()->subMinutes(10),
    'read_at' => null // Unread
]);

// Message 2: Reply from Main User
ChatMessage::create([
    'sender_id' => $mainUser->id,
    'receiver_id' => $buyer->id,
    'message' => 'Yes it is! Are you interested?',
    'ad_id' => $adId,
    'created_at' => now()->subMinutes(5),
    'read_at' => now()->subMinutes(4) // Read by buyer
]);

// Message 3: Reply from Buyer (Unread)
ChatMessage::create([
    'sender_id' => $buyer->id,
    'receiver_id' => $mainUser->id,
    'message' => 'Great! Can we meet tomorrow?',
    'ad_id' => $adId,
    'created_at' => now()->subMinutes(1),
    'read_at' => null // Unread
]);

echo "Seeded conversation with 3 messages.\n";
