<?php

namespace Database\Seeders;

use App\Enums\BookingStatus;
use App\Enums\CompanyStatus;
use App\Enums\SubscriptionStatus;
use App\Enums\UserRole;
use App\Models\Branch;
use App\Models\Company;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Plan;
use App\Models\Schedule;
use App\Models\Service;
use App\Models\ServiceCategory;
use App\Models\Subscription;
use App\Models\User;
use App\Support\Tenant;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DemoCompanySeeder extends Seeder
{
    public function run(): void
    {
        $plan = Plan::where('slug', 'professional')->firstOrFail();

        $company = Company::updateOrCreate(
            ['slug' => 'barberia-demo'],
            [
                'name'                  => 'Barbería Demo',
                'legal_name'            => 'Barbería Demo S.A.S.',
                'document_type'         => 'NIT',
                'document_number'       => '900.123.456-7',
                'email'                 => 'demo@reservapro.test',
                'phone'                 => '+573001234567',
                'whatsapp'              => '+573001234567',
                'address'               => 'Calle 100 # 15-20',
                'city'                  => 'Bogotá',
                'state'                 => 'Cundinamarca',
                'country'               => 'Colombia',
                'description'           => 'Barbería de demostración para ReservaPro.',
                'primary_color'         => '#0f172a',
                'secondary_color'       => '#06b6d4',
                'timezone'              => 'America/Bogota',
                'locale'                => 'es',
                'currency'              => 'COP',
                'status'                => CompanyStatus::Active,
                'plan_id'               => $plan->id,
                'trial_ends_at'         => now()->addDays(14),
                'subscription_starts_at' => now(),
                'subscription_ends_at'  => now()->addMonth(),
                'allow_guest_booking'   => true,
            ]
        );

        // Sede principal
        $branch = Branch::updateOrCreate(
            ['company_id' => $company->id, 'is_main' => true],
            [
                'name'      => 'Sede Principal',
                'slug'      => 'principal',
                'phone'     => $company->phone,
                'email'     => $company->email,
                'address'   => $company->address,
                'city'      => $company->city,
                'state'     => $company->state,
                'country'   => $company->country,
                'timezone'  => $company->timezone,
                'is_active' => true,
            ]
        );

        // Suscripción
        Subscription::updateOrCreate(
            ['company_id' => $company->id, 'plan_id' => $plan->id],
            [
                'status'                => SubscriptionStatus::Active,
                'billing_cycle'         => 'monthly',
                'amount'                => $plan->price_monthly,
                'currency'              => $plan->currency,
                'trial_starts_at'       => now()->subDays(14),
                'trial_ends_at'         => now(),
                'current_period_start'  => now(),
                'current_period_end'    => now()->addMonth(),
            ]
        );

        // Admin de la empresa
        $admin = User::updateOrCreate(
            ['email' => 'admin@barberia-demo.test'],
            [
                'company_id'        => $company->id,
                'branch_id'         => $branch->id,
                'name'              => 'Admin Demo',
                'password'          => Hash::make('password'),
                'phone'             => '+573001112233',
                'is_active'         => true,
                'email_verified_at' => now(),
            ]
        );
        if (! $admin->hasRole(UserRole::CompanyAdmin->value)) {
            $admin->assignRole(UserRole::CompanyAdmin->value);
        }

        // Setear tenant para que el resto se cree con company_id automático
        Tenant::set($company);

        try {
            // Categoría
            $cat = ServiceCategory::updateOrCreate(
                ['company_id' => $company->id, 'slug' => 'barberia'],
                ['name' => 'Barbería', 'icon' => 'scissors', 'color' => '#0f172a', 'is_active' => true]
            );

            // Servicios
            $services = [
                ['Corte clásico',     30, 25000],
                ['Corte + barba',     45, 35000],
                ['Arreglo de barba',  20, 15000],
                ['Tinte',             60, 60000],
            ];
            foreach ($services as [$name, $duration, $price]) {
                Service::updateOrCreate(
                    ['company_id' => $company->id, 'slug' => Str::slug($name)],
                    [
                        'service_category_id' => $cat->id,
                        'name'                => $name,
                        'price'               => $price,
                        'duration_minutes'    => $duration,
                        'is_active'           => true,
                        'is_public'           => true,
                    ]
                );
            }

            // Empleados
            $empleadosData = [
                ['Juan',  'Pérez',    'Barbero senior',   '#4f46e5'],
                ['Carlos','Gómez',    'Barbero',          '#10b981'],
                ['María', 'Rodríguez','Estilista',        '#f59e0b'],
            ];

            $servicesIds = Service::where('company_id', $company->id)->pluck('id');

            foreach ($empleadosData as [$first, $last, $position, $color]) {
                $emp = Employee::updateOrCreate(
                    ['company_id' => $company->id, 'first_name' => $first, 'last_name' => $last],
                    [
                        'branch_id'   => $branch->id,
                        'position'    => $position,
                        'color'       => $color,
                        'is_active'   => true,
                        'is_bookable' => true,
                    ]
                );
                $emp->services()->sync($servicesIds);

                // Horario L-V 09:00-18:00, S 09:00-14:00
                foreach (range(1, 6) as $weekday) {
                    Schedule::updateOrCreate(
                        ['company_id' => $company->id, 'employee_id' => $emp->id, 'weekday' => $weekday],
                        [
                            'branch_id'  => $branch->id,
                            'start_time' => '09:00:00',
                            'end_time'   => $weekday === 6 ? '14:00:00' : '18:00:00',
                            'is_active'  => true,
                        ]
                    );
                }
            }

            // Clientes demo
            $customers = [
                ['Andrea',  'López',     '+573101111111', 'andrea@example.com'],
                ['Felipe',  'Martínez',  '+573102222222', 'felipe@example.com'],
                ['Camila',  'Hernández', '+573103333333', 'camila@example.com'],
            ];
            foreach ($customers as [$f, $l, $p, $e]) {
                Customer::updateOrCreate(
                    ['company_id' => $company->id, 'phone' => $p],
                    ['first_name' => $f, 'last_name' => $l, 'email' => $e, 'is_active' => true]
                );
            }
        } finally {
            Tenant::clear();
        }
    }
}
