<?php

namespace Tests\Support\Categories;

use App\Models\CategoryModel;
use App\Models\TaskModel;

trait CategoryTestTrait
{
    protected function createCategory(int $userId, string $name): array
    {
        $model = new CategoryModel();
        $id    = $model->insert([
            'user_id'   => $userId,
            'name'      => $name,
            'is_active' => 1,
        ], true);
        $row = $model->find($id);
        $this->assertIsArray($row);

        return $row;
    }

    /**
     * @param array<string, mixed> $extra
     *
     * @return array<string, mixed>
     */
    protected function createTask(int $userId, int $categoryId, string $title = 'Sample task', array $extra = []): array
    {
        $model = new TaskModel();
        $id    = $model->insert(array_merge([
            'user_id'      => $userId,
            'category_id'  => $categoryId,
            'title'        => $title,
            'priority'     => 1,
            'due_date'     => null,
            'due_time'     => null,
            'is_recurring' => $extra['is_recurring'] ?? 0,
        ], $extra), true);
        $row = $model->find($id);
        $this->assertIsArray($row);

        return $row;
    }

    protected function createRecurrence(int $taskId): int
    {
        db_connect()->table('task_recurrence_rules')->insert([
            'task_id'          => $taskId,
            'recurrence_type'  => 'daily',
            'interval_value'   => 1,
            'start_date'       => date('Y-m-d'),
            'is_active'        => 1,
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s'),
        ]);

        return (int) db_connect()->insertID();
    }

    protected function createOccurrence(int $taskId, array $extra = []): int
    {
        db_connect()->table('task_occurrences')->insert(array_merge([
            'task_id'          => $taskId,
            'occurrence_date'  => date('Y-m-d'),
            'occurrence_time'  => '09:00:00',
            'status'           => 'pending',
            'is_deleted'       => 0,
            'created_at'       => date('Y-m-d H:i:s'),
            'updated_at'       => date('Y-m-d H:i:s'),
        ], $extra));

        return (int) db_connect()->insertID();
    }

    /**
     * @param array<string, mixed> $user
     *
     * @return array<string, mixed>
     */
    protected function authSession(array $user): array
    {
        return [
            'user_id'                      => (int) $user['id'],
            'email'                        => (string) $user['email'],
            'profile_onboarding_completed' => (int) $user['profile_onboarding_completed'],
        ];
    }
}
