<?php

namespace App\Console\Commands;

use App\Domain\Clinical\DefaultProcedures;
use App\Domain\Clinical\ToothChartService;
use App\Domain\WhatsApp\DefaultTemplates;
use App\Models\Dentist;
use App\Models\Patient;
use App\Models\Plan;
use App\Models\Tenant;
use App\Models\User;
use App\Support\Tenancy;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * A self-contained demo clinic for product evaluation: pre-populated with
 * dentists, patients, a chart, and procedures. Flagged is_demo so it never
 * counts toward MRR/metrics and can be reset/rebuilt at will.
 */
class CreateDemoClinic extends Command
{
    protected $signature = 'medibook:demo {--slug=demo} {--fresh : delete and rebuild}';

    protected $description = 'Create (or rebuild) the demo clinic for evaluation.';

    public function handle(): int
    {
        $slug = $this->option('slug');
        $plan = Plan::where('is_active', true)->firstOrFail();

        $existing = Tenant::withoutGlobalScope('tenant')->where('slug', $slug)->first();
        if ($existing) {
            if (! $this->option('fresh')) {
                $this->warn("Demo clinic '$slug' already exists. Use --fresh to rebuild.");

                return self::SUCCESS;
            }
            $existing->forceDelete();
        }

        DB::transaction(function () use ($slug, $plan) {
            $tenant = Tenant::create([
                'name' => 'Demo Dental Clinic',
                'slug' => $slug,
                'status' => 'trial',
                'is_demo' => true,
                'trial_ends_at' => now()->addYears(5), // demo never expires
                'whatsapp_number' => '+9647700000000',
            ]);

            app(Tenancy::class)->set($tenant);
            DefaultProcedures::seed($tenant);
            DefaultTemplates::seed($tenant);

            $tenant->subscription()->create([
                'plan_id' => $plan->id,
                'status' => 'trialing',
                'is_demo' => true,
                'starts_at' => now(),
                'current_period_ends_at' => now()->addYears(5),
                'mrr_iqd' => 0,
            ]);

            $owner = User::withoutEvents(fn () => User::create([
                'tenant_id' => $tenant->id,
                'name' => 'Demo Owner',
                'email' => 'demo@medibookai.com',
                'phone' => '+9647700000000',
                'password' => 'demo12345',
                'locale' => 'ar',
                'email_verified_at' => now(),
            ]));
            $owner->assignRole('clinic_owner');

            $dentists = collect([
                ['name' => 'Dr. Sara Ahmed', 'specialty' => 'General', 'color' => '#0EA5E9'],
                ['name' => 'Dr. Omar Hassan', 'specialty' => 'Orthodontist', 'color' => '#8B5CF6'],
            ])->map(fn ($d) => Dentist::create($d + ['status' => 'active']));

            foreach ($dentists as $dentist) {
                foreach ([0, 1, 2, 3, 4, 6] as $weekday) {
                    $dentist->schedules()->create(['weekday' => $weekday, 'start_time' => '09:00', 'end_time' => '17:00']);
                }
            }

            $patients = collect([
                ['full_name' => 'Ali Kareem', 'phone' => '07701112233'],
                ['full_name' => 'Fatima Noori', 'phone' => '07702223344'],
                ['full_name' => 'Hassan Jabbar', 'phone' => '07703334455'],
            ])->map(fn ($p) => Patient::create($p + ['source' => 'walk_in']));

            $chart = app(ToothChartService::class);
            $chart->record($patients[0], 16, 'caries');
            $chart->record($patients[0], 26, 'filling', \App\Enums\ToothState::Completed);
            $chart->record($patients[1], 36, 'crown', \App\Enums\ToothState::Planned);

            $this->components->info("Demo clinic ready: {$tenant->url('/login')}");
            $this->components->twoColumnDetail('Email', 'demo@medibookai.com');
            $this->components->twoColumnDetail('Password', 'demo12345');
        });

        app(Tenancy::class)->forget();

        return self::SUCCESS;
    }
}
