<?php

namespace Database\Seeders;

use App\Http\Controllers\SearchIndexController;
use App\Models\Admin;
use App\Models\Bank;
use App\Models\Locations\Location;
use App\Models\User;
use Database\Seeders\TaggableLocaleContextTableSeeder;
use Database\Seeders\TaggableLocalesTableSeeder;
use Database\Seeders\TaggableTagsTableSeeder;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Spatie\Permission\Models\Role;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        if ($this->command->confirm('Do you want to seed the base data (transaction types, permissions, countries, etc.)?')) {
            $this->call(TransactionTypesTableSeeder::class);
            $this->call(PermissionRoleSeeder::class);
            $this->call(CountriesTableSeeder::class);
            $this->call(CountryLocalesTableSeeder::class);
            $this->call(DivisionsTableSeeder::class);
            $this->call(DivisionLocalesTableSeeder::class);
            $this->call(CitiesTableSeeder::class);
            $this->call(CityLocalesTableSeeder::class);
            $this->call(DistrictsTableSeeder::class);
            $this->call(DistrictLocalesTableSeeder::class);
            $this->call(LanguagesTableSeeder::class);
            $this->call(LanguageCompetencesTableSeeder::class);
            $this->call(SocialsTableSeeder::class);
            $this->call(CountryLanguagesTableSeeder::class);
            $this->call(PostsTableSeeder::class);
            $this->call(PostTranslationsTableSeeder::class);
            $this->call(CategoriesTableSeeder::class);
            $this->call(ExtendCategoriesSeeder::class);
            $this->call(CategoryTranslationsTableSeeder::class);
            $this->call(ExtendCategoryTranslationsSeeder::class);
            $this->call(PlaceholderPostsSeeder::class);
            $this->call(MeetingsTableSeeder::class);
            $this->call(MediaTableSeeder::class);
            $this->call(LoveReactionTypesTableSeeder::class);

            // Seed Super-User with user id 1
            $superUser = User::create([
                'name' => 'Super-User',
                'full_name' => 'Super User',
                'email' => 'super-user@example.org',
                'email_verified_at' => Carbon::now(),
                'password' => Hash::make(timebank_config('init_passwords.super-user')),
                'profile_photo_path' => timebank_config('profiles.user.profile_photo_path_default'),
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $superAdmin = new Admin();
            $superAdmin->forceFill([
                'name' => 'Super-Admin',
                'full_name' => 'Super Admin',
                'email' => 'super-admin@example.org',
                'email_verified_at' => Carbon::now(),
                'password' => Hash::make(timebank_config('init_passwords.super-admin')),
                'profile_photo_path' => timebank_config('profiles.admin.profile_photo_path_default'),
            ])->save();

            $devAdmin = new Admin();
            $devAdmin->forceFill([
                'name' => 'Dev-Admin',
                'full_name' => 'Development Admin',
                'email' => 'dev-admin@example.org',
                'email_verified_at' => Carbon::now(),
                'password' => Hash::make(timebank_config('init_passwords.admin')),
                'profile_photo_path' => timebank_config('profiles.admin.profile_photo_path_default'),
            ])->save();

            $location = new Location(['city_id' => 305, 'division_id' => 12, 'country_id' => 1]);
            $superUser->locations()->save($location);
            $superAdmin->locations()->save($location);
            $devAdmin->locations()->save($location);

            // Seed Central Bank with bank id 1
            $bank = Bank::create([
                'name' => timebank_config('central_bank.name'),
                'full_name' => timebank_config('central_bank.full_name'),
                'email' => timebank_config('central_bank.email'),
                'email_verified_at' => Carbon::now(),
                'password' => bcrypt(timebank_config('init_passwords.bank')),
                'profile_photo_path' => timebank_config('profiles.bank.profile_photo_path_default'),
                'level' => 0,
            ]);

            // Create debit account for Central Bank
            $debitAccount = new \App\Models\Account();
            $debitAccount->name = __(timebank_config('accounts.debit.name', 'debit'));
            $debitAccount->limit_min = null;
            $debitAccount->limit_max = 0;
            $bank->accounts()->save($debitAccount);

            // attach admin and bank profile to super-user
            $superAdmin->users()->attach($superUser->id);
            $superUser->assignRole('super-admin');
            $devAdmin->users()->attach($superUser->id);
            $superUser->assignRole('admin');
            $roleBankManager = Role::findOrCreate('Bank\\' . $bank->id . '\\bank-manager', 'web');
            $bank->managers()->attach($superUser->id);
            $superUser->assignRole('Bank\\'.$bank->id.'\\bank-manager');
        }

        if ($this->command->confirm('Do you want to seed the example tags?')) {
            $this->call(TaggableTagsTableSeeder::class);
            $this->call(TaggableLocalesTableSeeder::class);
            $this->call(TaggableContextsTableSeeder::class);
            $this->call(TaggableLocaleContextTableSeeder::class);
        }

        // Migrate Cyclos database
        // If CYCLOS_DB env var is set (passed from seed.sh), skip the prompt and use it directly.
        $cyclosDb = env('CYCLOS_DB');
        $migrateCyclos = $cyclosDb
            ? true
            : $this->command->confirm('Do you want to migrate the cyclos database?');

        if ($migrateCyclos) {
            $cyclosArgs = $cyclosDb ? ['source_db' => $cyclosDb] : [];
            Artisan::call('migrate:cyclos', $cyclosArgs, $this->command->getOutput());

            if ($this->command->confirm('Do you want to migrate the cyclos profile data?')) {
                Artisan::call('migrate:cyclos-profiles', $cyclosArgs, $this->command->getOutput());
                Artisan::call('profiles:clean-about', [], $this->command->getOutput());
                Artisan::call('profiles:clean-cyclos-skills', [], $this->command->getOutput());
            }

            if ($this->command->confirm('Do you want to migrate the cyclos gift accounts?')) {
                Artisan::call('migrate:cyclos-gift-accounts', [], $this->command->getOutput());
            }

            if ($this->command->confirm('Do you want to assign the Dev-Admin role to an existing user that was imported?')) { // Clarified prompt
                $username = $this->command->ask('Enter the username of this user'); // Changed from $this->ask to $this->command->ask for consistency
                try {
                    $user = User::where('name', $username)->firstOrFail();
                    $devAdmin->users()->attach($user->id);
                    $user->assignRole('admin');
                    $this->command->info("Dev-Admin role assigned to user {$user->name}.");
                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    $this->command->error("User with username '{$username}' not found.");
                }
            }
        }

        if ($this->command->confirm('Do you want to (re-) create the Elasticsearch index? (This removes all existing data stored in the current index!)')) {
            $elasticsearchService = new SearchIndexController();
        }

        $this->command->info('Super-User email and password: super-user@example.org, ' .timebank_config('init_passwords.super-user'));

    }
}
