<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Tenant;
use App\Models\User;
use App\Services\TenantService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\Models\Tenant\Category;
use App\Models\Tenant\Unit;
use App\Models\Tenant\Brand;
use App\Models\Tenant\Product;
use App\Models\Tenant\Customer;
use App\Models\Tenant\Sale;

class DemoTenantSeeder extends Seeder
{
    protected $tenantService;

    public function __construct(TenantService $tenantService)
    {
        $this->tenantService = $tenantService;
    }

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $domain = 'demo.grocery-saas.local';
        
        // 1. Create Tenant (Central DB)
        $tenant = Tenant::firstOrCreate(
            ['domain' => $domain],
            [
                'name' => 'Demo Grocery Store',
                'database_name' => 'tenant_demo_grocery',
                'status' => 'active',
            ]
        );

        // Ensure DB exists and migrated (TenantService logic duplication/usage)
        // We use the service to create DB if not exists
        try {
            // Check if DB exists
            DB::connection('mysql')->statement("CREATE DATABASE IF NOT EXISTS `{$tenant->database_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            
            // Switch context to run migrations
            Config::set('database.connections.tenant.database', $tenant->database_name);
            DB::purge('tenant');
            
            \Illuminate\Support\Facades\Artisan::call('migrate', [
                '--database' => 'tenant',
                '--path' => 'database/migrations/tenant',
                '--force' => true,
            ]);

        } catch (\Exception $e) {
            $this->command->info('Tenant DB setup check: ' . $e->getMessage());
        }

        // 2. Create Manager User (Central DB)
        $user = User::firstOrCreate(
            ['email' => 'manager@demo.com'],
            [
                'name' => 'Demo Manager',
                'password' => Hash::make('password'),
                'tenant_id' => $tenant->id,
                'status' => 'active',
            ]
        );
        if (!$user->hasRole('Manager')) {
            $user->assignRole('Manager');
        }

        // 3. Seed Tenant Data
        $this->seedTenantData($tenant);
    }

    protected function seedTenantData(Tenant $tenant)
    {
        // Switch to Tenant Connection
        Config::set('database.connections.tenant.database', $tenant->database_name);
        DB::purge('tenant');
        DB::setDefaultConnection('tenant');

        // --- Categories ---
        $produce = Category::firstOrCreate(['name' => 'Produce']);
        $dairy = Category::firstOrCreate(['name' => 'Dairy & Eggs']);
        $beverages = Category::firstOrCreate(['name' => 'Beverages']);

        // --- Units ---
        $kg = Unit::firstOrCreate(['name' => 'Kilogram', 'short_name' => 'kg', 'type' => 'base']);
        $liter = Unit::firstOrCreate(['name' => 'Liter', 'short_name' => 'L', 'type' => 'base']);
        $piece = Unit::firstOrCreate(['name' => 'Piece', 'short_name' => 'pc', 'type' => 'base']);

        // --- Brands ---
        $farmFresh = Brand::firstOrCreate(['name' => 'Farm Fresh']);
        $localDairy = Brand::firstOrCreate(['name' => 'Local Dairy']);

        // --- Products & Variants ---
        $apple = Product::firstOrCreate([
            'name' => 'Red Apple',
            'unit_id' => $kg->id,
            'category_id' => $produce->id,
            'brand_id' => $farmFresh->id,
        ]);
        $appleVariant = $apple->variants()->firstOrCreate([
            'name' => 'Red Apple (Std)',
            'sku' => 'APL-001',
            'price' => 3.50,
            'cost' => 2.00,
        ]);

        $milk = Product::firstOrCreate([
            'name' => 'Whole Milk',
            'unit_id' => $liter->id,
            'category_id' => $dairy->id,
            'brand_id' => $localDairy->id,
        ]);
        $milkVariant = $milk->variants()->firstOrCreate([
            'name' => '1L Bottle',
            'sku' => 'MLK-001',
            'price' => 1.50,
            'cost' => 0.90,
        ]);

        // --- Customers ---
        $customer = Customer::firstOrCreate([
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'contact' => '555-1234',
        ]);

        // --- Sales History (Transactions) ---
        // Create 5 random sales
        for ($i = 0; $i < 5; $i++) {
            $sale = Sale::create([
                'customer_id' => $customer->id,
                'subtotal' => 0,
                'total' => 0,
                'status' => 'completed',
                'created_at' => now()->subDays($i),
            ]);

            // Add Items
            $qtyApple = rand(1, 5);
            $qtyMilk = rand(1, 2);

            $item1 = $sale->items()->create([
                'variant_id' => $appleVariant->id,
                'quantity' => $qtyApple,
                'price' => $appleVariant->price,
                'total' => $qtyApple * $appleVariant->price,
            ]);

            $item2 = $sale->items()->create([
                'variant_id' => $milkVariant->id,
                'quantity' => $qtyMilk,
                'price' => $milkVariant->price,
                'total' => $qtyMilk * $milkVariant->price,
            ]);

            $subtotal = $item1->total + $item2->total;
            $sale->update([
                'subtotal' => $subtotal,
                'total' => $subtotal
            ]);
        }

        // Restore Central Connection
        DB::setDefaultConnection('mysql');
    }
}
