<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Tenant;
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 SpecificTenantSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $databaseName = 'tenant_shop2grocery_saaslocal';
        
        $tenant = Tenant::where('database_name', $databaseName)->first();

        if (!$tenant) {
            $this->command->error("Tenant with database name '{$databaseName}' not found.");
            return;
        }

        $this->command->info("Seeding data for tenant: {$tenant->name} ({$tenant->database_name})");

        $this->seedTenantData($tenant);
        
        $this->command->info("Seeding completed for tenant: {$tenant->name}");
    }

    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']);
        $snacks = Category::firstOrCreate(['name' => 'Snacks']);

        // --- 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']);
        $pack = Unit::firstOrCreate(['name' => 'Pack', 'short_name' => 'pk', 'type' => 'base']);

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

        // --- 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,
        ]);
        
        $chips = Product::firstOrCreate([
            'name' => 'Potato Chips',
            'unit_id' => $pack->id,
            'category_id' => $snacks->id,
            'brand_id' => $tastySnacks->id,
        ]);
        $chipsVariant = $chips->variants()->firstOrCreate([
            'name' => 'Salted 50g',
            'sku' => 'CHP-001',
            'price' => 1.00,
            'cost' => 0.50,
        ]);

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

        // --- 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);
            $qtyChips = rand(1, 3);

            $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,
            ]);
            
            $item3 = $sale->items()->create([
                'variant_id' => $chipsVariant->id,
                'quantity' => $qtyChips,
                'price' => $chipsVariant->price,
                'total' => $qtyChips * $chipsVariant->price,
            ]);

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

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