<?php

namespace Daniv04\HaciendaPackage\Tests;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Daniv04\HaciendaPackage\Models\Receipt;
use Daniv04\HaciendaPackage\Models\ReceiptPayload;
use Daniv04\HaciendaPackage\HaciendaPackageServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;

abstract class TestCase extends OrchestraTestCase
{
    use RefreshDatabase;

    protected function getPackageProviders($app): array
    {
        return [
            HaciendaPackageServiceProvider::class,
        ];
    }

    protected function defineEnvironment($app): void
    {
        $app['config']->set('database.default', 'sqlite');
        $app['config']->set('database.connections.sqlite', [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ]);
        $app['config']->set('queue.default', 'sync');
        $app['config']->set('mail.default', 'array');

        // Package email config defaults for tests
        $app['config']->set('invoicing.send_email_on_accepted', false);
        $app['config']->set('invoicing.email_from_address', 'from@test.com');
        $app['config']->set('invoicing.email_from_name', 'Test Empresa');
    }

    /**
     * Create a Receipt with sensible test defaults.
     */
    protected function makeReceipt(array $overrides = []): Receipt
    {
        return Receipt::create(array_merge([
            'receipt_type'                => 'FE',
            'ui_key'                      => '50601202603262345600100010000000010000000011',
            'consecutive_number'          => '00100010000000010',
            'emission_date'               => now(),
            'receipt_status'              => 'sent',
            'hacienda_status'             => 'pending',
            'signed_xml'                  => '<xml>signed-content</xml>',
            'sell_condition'              => '01',
            'total_amount'                => 1000.000,
            'tax_amount'                  => 130.000,
            'total_discount'              => 0.000,
            'total_voucher'               => 1130.000,
            'currency'                    => 'CRC',
            'exchange_rate'               => 1.00000,
            'emissor_name'                => 'Empresa Test S.A.',
            'emissor_number'              => '3101234567',
            'emissor_type_identification' => 'juridical',
            'receiver_name'               => 'Cliente Test',
            'receiver_number'             => '104520963',
            'receiver_type_identification'=> 'physical',
        ], $overrides));
    }

    /**
     * Create a ReceiptPayload linked to a Receipt.
     * Pass $payloadOverrides to merge keys into the top-level payload array.
     */
    protected function makePayload(int $receiptId, array $payloadOverrides = []): ReceiptPayload
    {
        $default = [
            'Emisor' => [
                'Nombre'             => 'Empresa Test S.A.',
                'CorreoElectronico'  => ['empresa@test.com'],
                'Ubicacion'          => ['OtrasSenas' => 'San José, Costa Rica'],
            ],
            'Receptor' => [
                'Nombre'             => 'Cliente Test',
                'CorreoElectronico'  => 'cliente@test.com',
            ],
            'DetalleServicio' => [
                'LineaDetalle' => [
                    [
                        'NumeroLinea'     => 1,
                        'CodigoCABYS'     => '1234567',
                        'Detalle'         => 'Servicio de prueba',
                        'Cantidad'        => 1.00,
                        'UnidadMedida'    => 'Sp',
                        'PrecioUnitario'  => 1000.00,
                        'MontoTotalLinea' => 1130.00,
                        'Impuesto'        => [['Monto' => 130.00]],
                    ],
                ],
            ],
            'ResumenFactura' => [
                'TotalGravado'     => 1000.00,
                'TotalVentaNeta'   => 1000.00,
                'TotalImpuesto'    => 130.00,
                'TotalComprobante' => 1130.00,
            ],
            'Encabezado' => [
                'CondicionVenta'  => '01',
                'CodigoActividad' => '620100',
            ],
        ];

        return ReceiptPayload::create([
            'receipt_id'   => $receiptId,
            'receipt_type' => 'FE',
            'payload_json' => array_merge($default, $payloadOverrides),
        ]);
    }
}
