-- Check if columns exist before adding
PRAGMA table_info(Products);

-- Add new columns to Products if they don't exist
ALTER TABLE Products ADD COLUMN VariantCollectionId TEXT NULL;
ALTER TABLE Products ADD COLUMN VariantsJson TEXT NULL;

-- Add new column to OrderItems
ALTER TABLE OrderItems ADD COLUMN SelectedVariants TEXT NULL;

-- Create SalesLedgers table
CREATE TABLE IF NOT EXISTS SalesLedgers (
    Id TEXT NOT NULL PRIMARY KEY,
    OrderId TEXT NOT NULL,
    ProductId TEXT NOT NULL,
    ProductName TEXT NOT NULL,
    Quantity INTEGER NOT NULL,
    SalePriceFiat DECIMAL(18,2) NOT NULL,
    FiatCurrency TEXT NOT NULL,
    SalePriceBTC DECIMAL(18,8) NULL,
    Cryptocurrency TEXT NULL,
    SoldAt TEXT NOT NULL,
    FOREIGN KEY (OrderId) REFERENCES Orders(Id) ON DELETE RESTRICT,
    FOREIGN KEY (ProductId) REFERENCES Products(Id) ON DELETE RESTRICT
);

-- Create VariantCollections table
CREATE TABLE IF NOT EXISTS VariantCollections (
    Id TEXT NOT NULL PRIMARY KEY,
    Name TEXT NOT NULL,
    PropertiesJson TEXT NOT NULL,
    IsActive INTEGER NOT NULL,
    CreatedAt TEXT NOT NULL,
    UpdatedAt TEXT NOT NULL
);

-- Create indexes
CREATE INDEX IF NOT EXISTS IX_Products_VariantCollectionId ON Products(VariantCollectionId);
CREATE INDEX IF NOT EXISTS IX_SalesLedgers_OrderId ON SalesLedgers(OrderId);
CREATE INDEX IF NOT EXISTS IX_SalesLedgers_ProductId ON SalesLedgers(ProductId);
CREATE INDEX IF NOT EXISTS IX_SalesLedgers_ProductId_SoldAt ON SalesLedgers(ProductId, SoldAt);
CREATE INDEX IF NOT EXISTS IX_SalesLedgers_SoldAt ON SalesLedgers(SoldAt);
CREATE INDEX IF NOT EXISTS IX_VariantCollections_IsActive ON VariantCollections(IsActive);
CREATE INDEX IF NOT EXISTS IX_VariantCollections_Name ON VariantCollections(Name);

-- Update migration history
INSERT OR IGNORE INTO __EFMigrationsHistory (MigrationId, ProductVersion)
VALUES ('20250928014546_AddVariantCollectionsAndSalesLedger', '9.0.9');