<?php

namespace Tests\Unit;

use App\Models\Task;
use App\Models\TaskCollection;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TaskCollectionsRelationTest extends TestCase
{
    use RefreshDatabase;

    public function test_task_has_task_collections_relation(): void
    {
        $task = new Task;
        $relation = $task->taskCollections();

        $this->assertInstanceOf(BelongsToMany::class, $relation);
        $this->assertSame(['sort_order'], $relation->getPivotColumns());
    }

    public function test_reassign_tasks_moves_pivot_and_collection_id(): void
    {
        $collectionA = TaskCollection::factory()->create([
            'tenant_id' => null,
            'event_type_id' => null,
        ]);
        $collectionB = TaskCollection::factory()->create([
            'tenant_id' => null,
            'event_type_id' => null,
        ]);

        $task = Task::factory()->create([
            'tenant_id' => null,
            'event_type_id' => null,
            'collection_id' => $collectionA->id,
        ]);

        $collectionA->tasks()->attach($task->id);
        $collectionB->tasks()->attach($task->id);

        $collectionB->reassignTasks([$task->id]);

        $this->assertFalse($collectionA->tasks()->whereKey($task->id)->exists());
        $this->assertTrue($collectionB->tasks()->whereKey($task->id)->exists());
        $this->assertSame($collectionB->id, $task->fresh()->collection_id);
    }
}
