<?php

namespace Maestro\Core\Database\Seeders;

use Maestro\Core\Models\Organization;
use Maestro\Core\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        $permissionNames = [
            'activitylog.view',
            'settings.organization.view',
            'settings.organization.edit',
            'users.view',
            'users.create',
            'users.edit',
            'users.delete',
            'users.assign-roles',
            'roles.view',
            'roles.create',
            'roles.edit',
            'roles.delete',
        ];

        foreach ($permissionNames as $name) {
            Permission::firstOrCreate([
                'name' => $name,
                'guard_name' => 'web',
            ]);
        }

        $adminRole = Role::firstOrCreate([
            'name' => 'admin',
            'guard_name' => 'web',
        ]);

        $adminRole->givePermissionTo(Permission::where('guard_name', 'web')->whereIn('name', $permissionNames)->get());

        $organization = Organization::query()->updateOrCreate(
            ['id' => 1],
            [
                'name' => 'Maestro Demo BV',
                'company_name' => 'Maestro Demo BV',
                'street' => 'Stationsplein 1',
                'address_line_1' => 'Stationsplein 1',
                'city' => 'Amsterdam',
                'postal_code' => '1012 AB',
                'country_code' => 'nl',
                'country' => 'Nederland',
            ],
        );

        $user = User::query()->updateOrCreate(
            ['email' => 'demo@example.com'],
            [
                'name' => 'Demo Admin',
                'password' => Hash::make('password'),
                'organization_id' => $organization->id,
                'email_verified_at' => now(),
                'is_active' => true,
            ],
        );

        $user->syncRoles(['admin']);
    }
}
