-- =============================================
-- Author:		<YONATAN GAETE>
-- Create date: <26/03/2025>
-- Description:	<INSERTAR O ACTUALIZAR DESCUENTO AUTOMATICO POR SUCURSAL>
-- =============================================
CREATE PROCEDURE [dbo].[sp_Pvt_DescuentoAutomatico_Upsert]
    @sucursal INT,
    @montoCorte DECIMAL(18, 4),
    @porcDescuento INT,
    @activo INT,
    @RowsAffected INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    BEGIN TRY
        BEGIN TRANSACTION;
        
        SET @RowsAffected = 0;
        
        -- Versión optimizada del UPSERT
        UPDATE pvtConfiDescuentoAutomatico WITH (UPDLOCK, SERIALIZABLE)
        SET 
            montoCorte = @montoCorte,
            porcDescuento = @porcDescuento,
            activo = @activo
        WHERE 
            sucursal = @sucursal;
            
        SET @RowsAffected = @@ROWCOUNT;
        
        IF @RowsAffected = 0
        BEGIN
            INSERT INTO pvtConfiDescuentoAutomatico
                (sucursal, montoCorte, porcDescuento, activo)
            VALUES
                (@sucursal, @montoCorte, @porcDescuento, @activo);
                
            SET @RowsAffected = 1;
        END
        
        COMMIT TRANSACTION;
        
        RETURN 1; -- Éxito
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
            
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
        DECLARE @ErrorState INT = ERROR_STATE();
        
        RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
        RETURN 0; -- Error
    END CATCH
END