<?php

namespace Database\Seeders;

use App\Models\User;
use App\Services\CurrentContext;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Auth;

class DatabaseSeeder extends Seeder
{
    /**
     * Foundation for a clean install. Products, tenant categories and opening
     * stock are NOT seeded here — they are rebuilt from the legacy export by
     * the `legacy:migrate` command, which is run after `db:seed`. The one
     * exception is {@see SystemCategorySeeder}: that category is owned by the
     * application, not the tenant, and the POS resolves it by constant.
     */
    public function run(): void
    {
        // Run in the landlord/central context. This seeder's own queries (the
        // User lookup below) and the global vocabulary (menu, permissions,
        // geography) are cross-tenant, and every per-tenant seeder it calls
        // (LookupSeeder, PermissionsAndRolesSeeder, AccessControlSeeder,
        // CustomerSeeder, AdminUsersSeeder) already binds each tenant itself via
        // CurrentContext::runForTenant() when no tenant is in scope — so the
        // fail-closed TenantScope must not see this console run as "ambiguous".
        app(CurrentContext::class)->runWithoutTenant(function (): void {
            // Everything below builds a hyper-realistic demo dataset. It's seeded
            // while "logged in" as the Full Administrator: several models
            // (Invoice, Transaction, PurchaseOrder, PosSession, ReturnDoc) use the
            // BranchScoped global scope, which only bypasses filtering for a
            // full-admin actor — switching users mid-run risks silent empty reads
            // inside the service layer.
            $admin = User::where('email', 'admin@leo.com')->first();
            if ($admin) {
                Auth::login($admin);
            }

            $this->call([
                // Foundation: menu → permissions/system-roles → lookups →
                // application-owned categories → geography/currency/locale
                // reference data.
                MenuSeeder::class,
                PermissionsAndRolesSeeder::class,
                LookupSeeder::class,
                SystemCategorySeeder::class,
                GeographySeeder::class,
                ReferenceDataSeeder::class,

                // Mirrors CLOUDFLARE_R2_* from .env into storage_settings so the
                // credentials are visible/editable in Master Control → Storage
                // right after a deploy. Not required for uploads to work —
                // StorageConfig already falls back to .env on its own.
                StorageSettingSeeder::class,

                // Live data exported from production. AccessControlSeeder
                // provisions only the superadmin (see its superAdminUsers());
                // CustomerSeeder is intentionally NOT called — a fresh install
                // (and a test instance) starts with an empty customer book.
                AccessControlSeeder::class,   // superadmin + custom roles + overrides

                // Dev-only convenience accounts (admin@vellix.com / manager@vellix.lk =>
                // "password"). Runs last so it wins in local envs; skips in production.
                AdminUsersSeeder::class,

                // Landlord ("master control") operator account — separate table/guard.
                CentralAdminSeeder::class,
            ]);

            Auth::logout();
        });
    }
}
