<?php

namespace Database\Seeders;

use App\Models\KnowledgeBaseCategory;
use App\Models\KnowledgeBaseQuestion;
use App\Models\KnowledgeBaseAnswer;
use App\Models\User;
use Illuminate\Support\Str;

/**
 * KBQuestionSeederHelper
 *
 * Shared trait used by all per-category knowledge base question seeders.
 * Handles slug generation, question creation, answer creation, and count updates.
 * Each category seeder only needs to implement questions() returning the data array.
 */
trait KBQuestionSeederHelper
{
    /**
     * Seed questions for a given category slug.
     *
     * @param string $categorySlug
     * @param array  $questions
     * @return void
     */
    protected function seedQuestions(string $categorySlug, array $questions): void
    {
        $category = KnowledgeBaseCategory::where('slug', $categorySlug)->first();

        if (! $category) {
            $this->command->warn("  [SKIP] Category [{$categorySlug}] not found.");
            return;
        }

        $admin   = User::where('email', 'admin@sshia.org')->first();
        $manager = User::where('email', 'manager@sshia.org')->first();

        if (! $admin || ! $manager) {
            $this->command->warn('  [SKIP] admin@sshia.org or manager@sshia.org user not found.');
            return;
        }

        $seeded = 0;

        foreach ($questions as $qData) {
            $answers = $qData['answers'] ?? [];
            unset($qData['answers']);

            // Build a unique slug
            $baseSlug = Str::slug($qData['title']);
            $slug     = $baseSlug;
            $count    = KnowledgeBaseQuestion::withTrashed()
                ->where('slug', 'like', $baseSlug . '%')
                ->count();
            if ($count > 0) {
                $slug = $baseSlug . '-' . ($count + 1);
            }

            $question = KnowledgeBaseQuestion::updateOrCreate(
                ['title' => $qData['title']],
                array_merge($qData, [
                    'slug'          => $slug,
                    'category_id'   => $category->id,
                    'user_id'       => $admin->id,
                    'status'        => 'published',
                    'is_published'  => true,
                    'published_at'  => now()->subDays(rand(1, 180)),
                    'view_count'    => rand(30, 600),
                    'helpful_count' => rand(5, 80),
                ])
            );

            foreach ($answers as $i => $answerContent) {
                $authorId = ($i % 2 === 0) ? $admin->id : $manager->id;

                KnowledgeBaseAnswer::updateOrCreate(
                    ['question_id' => $question->id, 'sort_order' => $i],
                    [
                        'content'       => $answerContent,
                        'user_id'       => $authorId,
                        'is_published'  => true,
                        'is_accepted'   => ($i === 0),
                        'accepted_at'   => ($i === 0) ? now()->subDays(rand(1, 90)) : null,
                        'accepted_by'   => ($i === 0) ? $admin->id : null,
                        'helpful_count' => rand(3, 60),
                        'sort_order'    => $i,
                    ]
                );
            }

            $question->updateAnswerCount();
            $seeded++;
        }

        $category->updateQuestionsCount();
        $this->command->info("  [{$categorySlug}] {$seeded} questions seeded successfully.");
    }
}