<?php

namespace Tests\Unit;

use App\Models\AdminNotificationSubject;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class AdminNotificationSubjectModelTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Schema::dropIfExists('admin_notification_subjects');
        Schema::dropIfExists('users');

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('firstname')->nullable();
            $table->string('lastname')->nullable();
            $table->timestamps();
        });

        Schema::create('admin_notification_subjects', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('admin_id')->index();
            $table->string('subject');
            $table->timestamps();
        });
    }

    public function test_admin_relationship_returns_user(): void
    {
        DB::table('users')->insert([
            'id' => 10,
            'firstname' => 'Aisha',
            'lastname' => 'Saleh',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $subject = AdminNotificationSubject::create([
            'admin_id' => 10,
            'subject' => 'Weekly Summary',
        ]);

        $this->assertNotNull($subject->admin);
        $admin = $subject->admin;
        $adminId = is_array($admin) ? ($admin['id'] ?? null) : $admin->id;
        $this->assertSame(10, $adminId);
    }

    public function test_timestamps_are_set_on_create(): void
    {
        DB::table('users')->insert([
            'id' => 1,
            'firstname' => 'Fatima',
            'lastname' => 'Ali',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $subject = AdminNotificationSubject::create([
            'admin_id' => 1,
            'subject' => 'New Subject',
        ]);

        $fresh = $subject->fresh();
        $createdAt = is_array($fresh) ? ($fresh['created_at'] ?? null) : $fresh->created_at;
        $updatedAt = is_array($fresh) ? ($fresh['updated_at'] ?? null) : $fresh->updated_at;

        $this->assertNotNull($createdAt);
        $this->assertNotNull($updatedAt);
    }
}
