<?php

namespace App\Console\Commands;

use App\Models\Category;
use App\Models\Translation\WebinarTranslation;
use App\Models\Webinar;
use App\Support\PaymentCurrency;
use App\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class CreatePaymentTestWebinarCommand extends Command
{
    protected $signature = 'payment:create-test-courses';

    protected $description = 'Create/update payment test courses (1.5 USD payable, 0.2 USD shows rejection)';

    public function handle(): int
    {
        $teacher = User::query()
            ->whereIn('role_name', ['teacher', 'organization', 'admin'])
            ->orderByRaw("FIELD(role_name, 'admin', 'teacher', 'organization')")
            ->first();

        if (!$teacher) {
            $this->error('No teacher/admin user found.');

            return 1;
        }

        $category = Category::query()->whereNull('parent_id')->value('id')
            ?? Category::query()->value('id');

        if (!$category) {
            $this->error('No category found. Create a category first.');

            return 1;
        }

        $thumb = '/store/1/default_images/webinar_placeholder.png';
        if (!file_exists(public_path($thumb))) {
            $thumb = '/assets/default/img/course/course-placeholder.png';
        }

        $courses = [
            [
                'slug' => 'payment-test-course',
                'title' => 'دورة تجربة الدفع (تعمل)',
                'price' => 1.5,
                'currency' => PaymentCurrency::USD,
                'description' => 'دورة للاختبار — السعر 1.5 دولار (أكبر من حد EasyKash). استخدمها لتجربة الدفع الناجح.',
            ],
            [
                'slug' => 'payment-test-reject',
                'title' => 'دورة تجربة الرفض (0.2$)',
                'price' => 0.2,
                'currency' => PaymentCurrency::USD,
                'description' => 'دورة للاختبار — السعر 0.2 دولار لعرض رسالة سبب الرفض (أقل من حد البوابة).',
            ],
        ];

        DB::beginTransaction();

        try {
            foreach ($courses as $data) {
                $webinar = $this->upsertCourse($data, (int) $teacher->id, (int) $category, $thumb);
                $this->line('OK: ' . $webinar->title . ' → /course/' . $webinar->slug . ' (' . $data['price'] . ' ' . $data['currency'] . ')');
            }

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            $this->error($e->getMessage());

            return 1;
        }

        $this->line('');
        $this->info('جرّب الشراء من الروابط أعلاه بعد تسجيل الدخول.');

        return 0;
    }

    private function upsertCourse(array $data, int $teacherId, int $categoryId, string $thumb): Webinar
    {
        $attributes = [
            'type' => Webinar::$course,
            'slug' => $data['slug'],
            'teacher_id' => $teacherId,
            'creator_id' => $teacherId,
            'thumbnail' => $thumb,
            'image_cover' => $thumb,
            'category_id' => $categoryId,
            'duration' => 60,
            'price' => $data['price'],
            'status' => Webinar::$active,
            'updated_at' => time(),
        ];

        if (Schema::hasColumn('webinars', 'currency')) {
            $attributes['currency'] = PaymentCurrency::normalize($data['currency']);
        }

        $webinar = Webinar::query()->where('slug', $data['slug'])->where('id', '>', 0)->first();

        if ($webinar) {
            $webinar->update($attributes);
        } else {
            $nextId = (int) (Webinar::max('id') ?? 0) + 1;
            $attributes['id'] = $nextId;
            $attributes['created_at'] = time();
            $attributes['support'] = 0;
            $attributes['certificate'] = 0;
            $attributes['downloadable'] = 0;
            $attributes['partner_instructor'] = 0;
            $attributes['subscribe'] = 0;
            $attributes['forum'] = 0;
            DB::table('webinars')->insert($attributes);
            $webinar = Webinar::find($nextId);
        }

        if (empty($webinar) || empty($webinar->id)) {
            throw new \RuntimeException('Failed to create webinar with a valid id.');
        }

        $locale = mb_strtolower(getDefaultLocale());

        WebinarTranslation::updateOrCreate(
            ['webinar_id' => $webinar->id, 'locale' => $locale],
            [
                'title' => $data['title'],
                'description' => $data['description'],
                'seo_description' => $data['title'],
            ]
        );

        return $webinar->refresh();
    }
}
