<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateChatsTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // create conversations table
        Schema::create('conversations', function (Blueprint $table) {
            $table->id();
            $table->enum('type', ['direct', 'group'])->default('direct');
            $table->string('name')->nullable();
            $table->timestamps();
        });

        //participants table
        Schema::create('participants', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('conversation_id');
            $table->unsignedBigInteger('user_id');
            $table->foreign('conversation_id')->references('id')->on('conversations');
            $table->timestamps();
        });

        //messages table
        Schema::create('messages', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('conversation_id');
            $table->unsignedBigInteger('user_id');
            $table->string('content_type')->nullable();
            $table->text('content')->nullable();
            $table->timestamp('sent_at')->currentTimestamp();
            $table->foreign('conversation_id')->references('id')->on('conversations');
            $table->timestamps();
        });
        //MessageStatus
        Schema::create('message_status', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('message_id');
            $table->unsignedBigInteger('user_id');
            $table->enum('delivery_status', ['pending', 'delivered'])->default('pending');
            $table->timestamp('delivered_at')->nullable();
            $table->enum('read_status', ['unread', 'read'])->default('unread');
            $table->timestamp('read_at')->nullable();
            $table->foreign('message_id')->references('id')->on('messages');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('conversations');
        Schema::dropIfExists('participants');
        Schema::dropIfExists('messages');
        Schema::dropIfExists('message_status');
    }
}
