-- Run this script to update the database schema

-- Update Listings table
ALTER TABLE Listings ADD PublicationStartDate DATETIME2 NULL;
ALTER TABLE Listings ADD ApprovedAt DATETIME2 NULL;
ALTER TABLE Listings ADD IsFeatured BIT NOT NULL DEFAULT 0;
ALTER TABLE Listings ADD FeaturedExpiry DATETIME2 NULL;
ALTER TABLE Listings ADD AllowContact BIT NOT NULL DEFAULT 1;

-- Update Users table
ALTER TABLE Users ADD BillingName NVARCHAR(200) NULL;
ALTER TABLE Users ADD BillingAddress NVARCHAR(500) NULL;
ALTER TABLE Users ADD BillingTaxId NVARCHAR(50) NULL;
ALTER TABLE Users ADD BillingTaxType NVARCHAR(50) NULL;
ALTER TABLE Users ADD ClientId INT NULL;
ALTER TABLE Users ADD FailedLoginAttempts INT NOT NULL DEFAULT 0;
ALTER TABLE Users ADD LockoutEnd DATETIME NULL;
ALTER TABLE Users ADD MustChangePassword BIT NOT NULL DEFAULT 1;
ALTER TABLE Users ADD IsActive BIT NOT NULL DEFAULT 1;
ALTER TABLE Users ADD LastLogin DATETIME NULL;
ALTER TABLE Users ADD GoogleId NVARCHAR(255) NULL;
ALTER TABLE Users ADD IsMfaEnabled BIT NOT NULL DEFAULT 0;
ALTER TABLE Users ADD MfaSecret NVARCHAR(255) NULL;
ALTER TABLE Users ADD Phone NVARCHAR(50) NULL;

-- Create Coupons table
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Coupons' and xtype='U')
BEGIN
    CREATE TABLE Coupons (
        Id INT IDENTITY(1,1) PRIMARY KEY,
        Code NVARCHAR(50) NOT NULL,
        DiscountType NVARCHAR(20) NOT NULL,
        DiscountValue DECIMAL(18,2) NOT NULL,
        ExpiryDate DATETIME2 NULL,
        UsageCount INT NOT NULL DEFAULT 0,
        MaxUsages INT NULL,
        IsActive BIT NOT NULL DEFAULT 1,
        CreatedAt DATETIME2 NOT NULL DEFAULT GETUTCDATE()
    );
    CREATE UNIQUE INDEX IX_Coupons_Code ON Coupons(Code);
END

-- Data Migration and Consolidation
-- Copy clients to users if they don't exist
INSERT INTO Users (Username, PasswordHash, Role, Email, BillingName, BillingTaxId, BillingAddress, Phone, MustChangePassword, IsActive)
SELECT 
    ISNULL(DniOrCuit, Name), 'N/A', 'Client', Email, Name, DniOrCuit, Address, Phone, 0, 1
FROM Clients
WHERE DniOrCuit NOT IN (SELECT BillingTaxId FROM Users WHERE BillingTaxId IS NOT NULL);

-- Update Listings to point to new User IDs
UPDATE l
SET l.ClientId = u.Id
FROM Listings l
JOIN Clients c ON l.ClientId = c.Id
JOIN Users u ON c.DniOrCuit = u.BillingTaxId;

-- Drop foreign keys referencing Clients
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += 'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)) + 
               ' DROP CONSTRAINT ' + QUOTENAME(name) + ';'
FROM sys.foreign_keys
WHERE referenced_object_id = OBJECT_ID('Clients');

IF @sql <> '' EXEC sp_executesql @sql;

-- DROP obsolete table
IF EXISTS (SELECT * FROM sysobjects WHERE name='Clients' and xtype='U')
    DROP TABLE Clients;
