<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Mtc\MercuryDataModels\Tenant as MercuryDataModelsTenant;

class SeedContactFormForAllTenants extends Command
{
    protected $signature = 'tenants:seed-contact-form';
    protected $description = 'Run ContactFormSeeder for each tenant';

    public function handle(): void
    {
        $this->info('Seeding ContactFormSeeder for all tenants...');

        tenancy()
            ->runForMultiple(MercuryDataModelsTenant::query()->whereNull('suspended_at')->get(), function ($tenant) {
                $this->info("Seeding for tenant: {$tenant->id}");

                // Truncate necessary tables before seeding
                $this->truncateTables();

                // Run all enquiry seeders
                $this->callSeeders();
            });

        $this->info('Seeding completed for all tenants.');
    }

    private function truncateTables()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        DB::table('enquiry_types')->truncate();
        DB::table('forms')->truncate();
        DB::table('form_sections')->truncate();
        DB::table('form_questions')->truncate();

        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        $this->info('Truncated relevant tables.');
    }

    private function callSeeders()
    {
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\EnquiryTypeSeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\GeneralEnquirySeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\UsedVehicleEnquirySeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\NewVehicleEnquirySeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\BookTestDriveNewSeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\BookTestDriveUsedSeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\SellMyCarEnquirySeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\PartsAccessoriesEnquirySeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\VacancyEnquirySeeder::class]);
        Artisan::call('db:seed', ['--class' => \Database\Seeders\Tenant\FinanceEnquirySeeder::class]);

        $this->info('Ran all enquiry seeders.');
    }
}
