<?php

use Illuminate\Support\Facades\Blade;

it('loads entity-specific crud form resources before the shared fallback', function () {
    $html = Blade::render('@include("administracion.crud.partials.form-fields", ["entity" => "bienes", "entityCrudView" => "administracion.crud.entities.bienes", "editableColumns" => ["descripcion", "mesesEntrega", "tiempoRetorno", "codigo"], "errors" => new \Illuminate\Support\ViewErrorBag(), "fieldOptions" => [], "formColumnLabels" => []])');

    expect($html)->toContain('Descripcion del bien');
    expect($html)->toContain('Codigo interno o de inventario');
    expect($html)->not->toContain('mesesEntrega');
    expect($html)->not->toContain('tiempoRetorno');
    expect($html)->not->toContain('name="costo"');
});

it('keeps bienes delivery fields outside create mode', function () {
    $html = Blade::render('@include("administracion.crud.partials.form-fields", ["entity" => "bienes", "entityCrudView" => "administracion.crud.entities.bienes", "editableColumns" => ["descripcion", "mesesEntrega", "tiempoRetorno", "codigo"], "currentFormMode" => "edit", "errors" => new \Illuminate\Support\ViewErrorBag(), "fieldOptions" => [], "formColumnLabels" => []])');

    expect($html)->toContain('name="mesesEntrega"');
    expect($html)->toContain('name="tiempoRetorno"');
});

it('uses the shared fallback resources for generic crud entities', function () {
    $html = Blade::render('@include("administracion.crud.partials.form-fields", ["entity" => "dependencias", "entityCrudView" => "administracion.crud.entities.dependencias", "editableColumns" => ["nombre"], "errors" => new \Illuminate\Support\ViewErrorBag(), "fieldOptions" => [], "formColumnLabels" => []])');

    expect($html)->toContain('name="nombre"');
    expect($html)->not->toContain('Codigo SAP del bien');
});

it('loads custom form resources for precios por bien', function () {
    $editableColumns = ['bien_id', 'precio', 'porcentaje_utilidad', 'fecha_registro'];
    $currentFormMode = 'create';

    $resources = require resource_path('views/administracion/crud/entities/precios-por-bien/recursos-formulario.php');

    expect($resources['placeholders']['bien_id'])->toBe('Seleccione el bien')
        ->and($resources['placeholders']['porcentaje_utilidad'])->toBe('Porcentaje de utilidad aplicado')
        ->and($resources['dateFieldNames'])->toContain('fecha_registro')
        ->and($resources['numericFieldNames'])->toContain('precio');
});

    it('applies utilidad bounds in precios por bien modal fields', function () {
        $html = Blade::render('@include("administracion.crud.partials.form-fields", ["entity" => "precios-por-bien", "entityCrudView" => "administracion.crud.entities.precios-por-bien", "editableColumns" => ["bien_id", "precio", "porcentaje_utilidad", "fecha_registro"], "errors" => new \Illuminate\Support\ViewErrorBag(), "fieldOptions" => ["bien_id" => [1 => "ABS00001 - Arroz"]], "formColumnLabels" => []])');

        expect($html)->toContain('name="porcentaje_utilidad"')
        ->and($html)->toContain('min=0')
        ->and($html)->toContain('max=100')
        ->and($html)->toContain('name="precio"')
        ->and($html)->toContain('min=0.01');
    });

it('renders extracted page form partials for users and bienes', function () {
    $baseData = [
        'record' => null,
        'defaultValues' => [],
        'fieldOptions' => [],
        'errors' => new \Illuminate\Support\ViewErrorBag(),
        'dateFieldNames' => ['fechaIngreso', 'fechaOperacion'],
        'numericFieldNames' => ['relacionUnidades', 'peso', 'costo', 'tiempoRetorno', 'mesesEntrega'],
        'fieldLabel' => static fn (string $column): string => ucfirst(str_replace('_', ' ', $column)),
        'isImportantField' => static fn (string $column): bool => in_array($column, ['cedula', 'descripcion'], true),
        'placeholders' => [],
        'mode' => 'create',
        'entity' => 'users',
        'isSitiosEntity' => false,
        'hasResponsableReference' => false,
        'hasCedulaUsuarioReference' => false,
        'hasCedulaResponsableReference' => false,
        'isTallasUniformesEntity' => false,
    ];

    $userHtml = view('administracion.crud.entities.users.campos-formulario-pagina', array_merge($baseData, [
        'credentialColumns' => ['cedula', 'password'],
        'generalPrimaryColumn' => 'nombre',
        'generalCompactColumns' => ['cargo'],
        'usuarioPhotoUrl' => null,
        'placeholders' => [
            'cedula' => 'Numero de Cedula',
            'password' => 'clave..',
            'nombre' => 'Nombre completo del personal',
            'cargo' => 'Cargo',
        ],
    ]))->render();

    $bienesHtml = view('administracion.crud.entities.bienes.campos-formulario-pagina', array_merge($baseData, [
        'entity' => 'bienes',
        'generalColumns' => ['descripcion', 'codigo', 'relacionUnidades', 'peso'],
        'placeholders' => [
            'descripcion' => 'Descripcion del bien',
            'codigo' => 'Codigo interno o de inventario',
            'relacionUnidades' => 'Cantidad por unidad',
            'peso' => 'Peso por unidad en kg',
        ],
    ]))->render();

    $bienesModalHtml = Blade::render('@include("administracion.crud.partials.comun.formulario.dominios-modal.bienes", ["entity" => "bienes", "generalColumns" => ["descripcion", "codigo", "peso"], "errors" => new \Illuminate\Support\ViewErrorBag(), "placeholders" => ["codigo" => "Codigo interno o de inventario"], "formColumnLabels" => ["codigo" => "Codigo"], "isSitiosEntity" => false, "isTallasUniformesEntity" => false, "hasResponsableReference" => false, "hasCedulaUsuarioReference" => false, "hasCedulaResponsableReference" => false, "fieldOptions" => [], "dateFieldNames" => ["fechaIngreso", "fechaOperacion"], "numericFieldNames" => ["relacionUnidades", "peso", "costo", "tiempoRetorno", "mesesEntrega"]])');

    expect($userHtml)->toContain('id="fotoUsuario"');
    expect($userHtml)->toContain('name="cedula"');
    expect($bienesHtml)->toContain('id="pesoTotalPreview"');
    expect($bienesHtml)->toContain('id="codigo"');
    expect($bienesHtml)->toContain('Si el codigo está vacio, se generara automaticamente con el prefijo ABS');
    expect($bienesHtml)->toContain('name="fotoBienes"');
    expect($bienesModalHtml)->toContain('id="modal_codigo"');
    expect($bienesModalHtml)->toContain('Si el codigo está vacio, se generara automaticamente con el prefijo ABS');
});