<?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']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\GeneralEnquirySeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\UsedVehicleEnquirySeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\NewVehicleEnquirySeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\BookTestDriveNewSeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\BookTestDriveUsedSeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\SellMyCarEnquirySeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\PartsAccessoriesEnquirySeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\VacancyEnquirySeeder']);
        Artisan::call('db:seed', ['--class' => 'Database\\Seeders\\Tenant\\FinanceEnquirySeeder']);

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