<?php

namespace Database\Seeders;

use App\Models\Company;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;

/**
 * Runs once, right after the tenancy migrations. Two jobs:
 *
 *   1. Every row that existed before multi-tenancy — every user, course,
 *      instructor, the one settings row, everything — gets assigned to a
 *      single "root" Company (ABIC_E-Learning) so nothing is left orphaned.
 *   2. The platform's own operator account is created: is_root = true,
 *      company_id = null. It doesn't belong to any tenant and today grants
 *      no access to anything — Phase 2 builds the SaaS control panel and
 *      its middleware behind that flag.
 *
 * Idempotent: safe to re-run. It updates the existing root company/admin by
 * slug/email rather than inserting duplicates.
 */
class CreateRootCompanySeeder extends Seeder
{
    /**
     * Mirrors the table list in
     * 2026_08_08_100300_add_company_id_to_tenant_content_tables.php.
     */
    private array $tenantTables = [
        'categories', 'courses', 'instructors', 'exams', 'quizzes', 'coupons',
        'invoices', 'blogs', 'articles', 'pages', 'testimonials', 'offer_banners',
        'notifications', 'payment_gateways', 'languages', 'frames', 'subscribers',
        'social_media', 'plans', 'manage_certificates', 'contact_messages',
        'newslatter_subscriptions',
    ];

    public function run(): void
    {
        DB::transaction(function () {
            $company = Company::updateOrCreate(
                ['slug' => 'abic-e-learning'],
                ['name' => 'ABIC_E-Learning', 'status' => 'active']
            );

            if (Schema::hasColumn('settings', 'company_id')) {
                DB::table('settings')->whereNull('company_id')->update(['company_id' => $company->id]);
            }

            if (Schema::hasColumn('users', 'company_id')) {
                DB::table('users')->whereNull('company_id')->update(['company_id' => $company->id]);
            }

            foreach ($this->tenantTables as $table) {
                if (Schema::hasTable($table) && Schema::hasColumn($table, 'company_id')) {
                    DB::table($table)->whereNull('company_id')->update(['company_id' => $company->id]);
                }
            }

            $this->seedRootAdmin();
        });
    }

    private function seedRootAdmin(): void
    {
        $email = env('SAAS_ROOT_ADMIN_EMAIL');
        $password = env('SAAS_ROOT_ADMIN_PASSWORD');

        if (!$email || !$password) {
            $this->command?->warn(
                'SAAS_ROOT_ADMIN_EMAIL / SAAS_ROOT_ADMIN_PASSWORD are not set in .env — skipped creating the SaaS root admin.'
            );

            return;
        }

        User::withTrashed()->updateOrCreate(
            ['email' => $email],
            [
                'name' => env('SAAS_ROOT_ADMIN_NAME', 'ABIC_E-Learning Admin'),
                'phone' => null,
                'password' => Hash::make($password),
                'company_id' => null,
                'is_root' => true,
                'is_active' => true,
                'is_admin' => false,
                'email_verified_at' => now(),
                'deleted_at' => null,
            ]
        );
    }
}
