<?php

namespace App\Domains\Admin\Actions\CreateTenant;

use App\Models\AvailablePaymentMethod;
use App\Models\PaymentMethod;
use App\Models\Tenant;

class CreateTenantAction
{
    public function __construct(private CreateTenantRequest $request)
    {
    }

    public function execute(): CreateTenantResponse
    {
        $response = new CreateTenantResponse();

        $tenant = Tenant::create([
            'name' => $this->request->name,
            'slug' => $this->request->slug,
            'url' => $this->request->url,
            'email' => '',
            'email_finance' => '',
            'account_name' => '',
            'account_iban' => '',
            'account_bic' => '',
            'city' => '',
            'postcode' => '',
            'is_active_local_group' => true,
            'has_active_instance' => true,
        ]);

        $paymentMethodDefaults = PaymentMethod::defaults();
        foreach (PaymentMethod::all() as $paymentMethod) {
            $defaults = $paymentMethodDefaults[$paymentMethod->slug] ?? ['name' => $paymentMethod->slug, 'description' => null, 'configuration' => []];

            AvailablePaymentMethod::create([
                'tenant' => $tenant->slug,
                'slug' => $paymentMethod->slug,
                'name' => $defaults['name'],
                'description' => $defaults['description'],
                'active' => true,
                'configuration' => PaymentMethod::sanitizeConfiguration($paymentMethod->slug, $defaults['configuration'] ?? []),
            ]);
        }

        $response->success = true;
        $response->message = 'Stamm wurde angelegt.';
        $response->slug = $tenant->slug;

        return $response;
    }
}
