<?php

namespace App\Modules\Billing;

use App\Models\InvoiceBilling;
use App\Modules\Billing\Foriba\ForibaModule;
use App\Modules\Billing\Gib\GibModule;
use App\Modules\Billing\Izibiz\IzibizModule;
use App\Modules\Billing\Logo\LogoModule;
use App\Modules\Billing\LogoIsbasi\LogoIsbasiModule;
use App\Modules\Billing\Parasut\ParasutModule;
use App\Modules\Billing\Uyumsoft\UyumsoftModule;
use InvalidArgumentException;

class BillingModuleFactory
{
    /**
     * Modül adına göre modül sınıfı oluştur
     */
    public static function create(string $moduleName, array $settings = [], array $fieldMappings = []): BillingModuleInterface
    {
        return match ($moduleName) {
            'gib' => new GibModule($settings, $fieldMappings),
            'logo' => new LogoModule($settings, $fieldMappings),
            'logo_isbasi' => new LogoIsbasiModule($settings, $fieldMappings),
            'parasut' => new ParasutModule($settings, $fieldMappings),
            // PRC-1069: GİB e-fatura entegratörleri (Uyumsoft/İzibiz SOAP, Foriba/Sovos REST).
            'foriba' => new ForibaModule($settings, $fieldMappings),
            'izibiz' => new IzibizModule($settings, $fieldMappings),
            'uyumsoft' => new UyumsoftModule($settings, $fieldMappings),
            default => throw new InvalidArgumentException(__('admin/modules.factory_unsupported_module', ['module' => $moduleName]))
        };
    }

    /**
     * InvoiceBilling model'den modül oluştur
     */
    public static function createFromModel(InvoiceBilling $invoiceBilling): BillingModuleInterface
    {
        $module = self::create(
            $invoiceBilling->name,
            $invoiceBilling->settings ?? [],
            $invoiceBilling->mapping_fields ?? []
        );

        // PRC-1066: OAuth modülleri (Parasut) token'ı yenilediğinde
        // InvoiceBilling.settings'e geri yazsın — modül modeli bilmez, closure köprüler.
        if (method_exists($module, 'onTokenRefresh')) {
            $module->onTokenRefresh(function (array $delta) use ($invoiceBilling) {
                $invoiceBilling->settings = array_merge($invoiceBilling->settings ?? [], $delta);
                $invoiceBilling->save();
            });
        }

        return $module;
    }

    /**
     * Tüm desteklenen modülleri listele
     */
    public static function getSupportedModules(): array
    {
        return [
            'gib' => [
                'name' => __('admin/modules.factory_gib_name'),
                'type' => 'e-invoice',
                'description' => __('admin/modules.factory_gib_description'),
                'class' => GibModule::class,
            ],
            'logo' => [
                'name' => __('admin/modules.factory_logo_name'),
                'type' => 'e-invoice',
                'description' => __('admin/modules.factory_logo_description'),
                'class' => LogoModule::class,
            ],
            'logo_isbasi' => [
                'name' => __('admin/modules.factory_logo_isbasi_name'),
                'type' => 'e-invoice',
                'description' => __('admin/modules.factory_logo_isbasi_description'),
                'class' => LogoIsbasiModule::class,
            ],
            'parasut' => [
                'name' => __('admin/modules.factory_parasut_name'),
                'type' => 'e-invoice',
                'description' => __('admin/modules.factory_parasut_description'),
                'class' => ParasutModule::class,
            ],
            // PRC-1069 — GİB e-fatura entegratörleri.
            'foriba' => [
                'name' => __('admin/modules.factory_foriba_name'),
                'type' => 'e-invoice',
                'description' => __('admin/modules.factory_foriba_description'),
                'class' => ForibaModule::class,
            ],
            'izibiz' => [
                'name' => __('admin/modules.factory_izibiz_name'),
                'type' => 'e-invoice',
                'description' => __('admin/modules.factory_izibiz_description'),
                'class' => IzibizModule::class,
            ],
            'uyumsoft' => [
                'name' => __('admin/modules.factory_uyumsoft_name'),
                'type' => 'e-invoice',
                'description' => __('admin/modules.factory_uyumsoft_description'),
                'class' => UyumsoftModule::class,
            ],
        ];
    }

    /**
     * Modül tipine göre desteklenen modülleri listele
     */
    public static function getModulesByType(string $type): array
    {
        $modules = self::getSupportedModules();

        return array_filter($modules, function ($module) use ($type) {
            return $module['type'] === $type;
        });
    }

    /**
     * Modül adının geçerli olup olmadığını kontrol et
     */
    public static function isValidModule(string $moduleName): bool
    {
        return array_key_exists($moduleName, self::getSupportedModules());
    }

    /**
     * Modül sınıfının var olup olmadığını kontrol et
     */
    public static function moduleExists(string $moduleName): bool
    {
        if (! self::isValidModule($moduleName)) {
            return false;
        }

        $moduleInfo = self::getSupportedModules()[$moduleName];

        return class_exists($moduleInfo['class']);
    }
}
