SET XACT_ABORT ON;
BEGIN TRANSACTION;

IF OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.py_BarcodePickingListSkip (
        ID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_py_BarcodePickingListSkip PRIMARY KEY,
        Documento varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
        Pallet varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
        IDStato int NOT NULL,
        IDOperatore int NOT NULL,
        DataOra datetime2(0) NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_DataOra DEFAULT SYSDATETIME(),
        Motivo nvarchar(200) NULL,
        Risolto bit NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_Risolto DEFAULT 0,
        RisoltoDa int NULL,
        RisoltoDataOra datetime2(0) NULL
    );
END;

IF NOT EXISTS (
    SELECT 1
    FROM sys.indexes
    WHERE name = N'UX_py_BarcodePickingListSkip_Open'
      AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
)
BEGIN
    CREATE UNIQUE INDEX UX_py_BarcodePickingListSkip_Open
        ON dbo.py_BarcodePickingListSkip (Documento, Pallet, IDStato)
        WHERE Risolto = 0;
END;

IF NOT EXISTS (
    SELECT 1
    FROM sys.indexes
    WHERE name = N'IX_py_BarcodePickingListSkip_Queue'
      AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
)
BEGIN
    CREATE INDEX IX_py_BarcodePickingListSkip_Queue
        ON dbo.py_BarcodePickingListSkip (IDStato, Documento, Pallet, Risolto);
END;

COMMIT TRANSACTION;
