-- ===========================================
-- SQL Server Setup Script for AccManager
-- Database: AccManager
-- Server: 172.20.235.176
-- ===========================================

-- Create Database
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'AccManager')
BEGIN
    CREATE DATABASE AccManager;
    PRINT 'Database AccManager created successfully.';
END
ELSE
BEGIN
    PRINT 'Database AccManager already exists.';
END
GO

USE AccManager;
GO

-- ===========================================
-- 1. CREATE USERS TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Users')
BEGIN
    CREATE TABLE Users (
        UserId INT PRIMARY KEY IDENTITY(1,1),
        Username NVARCHAR(50) UNIQUE NOT NULL,
        Password NVARCHAR(255) NOT NULL,
        Email NVARCHAR(100),
        FullName NVARCHAR(100),
        Role NVARCHAR(50) NOT NULL,
        Status NVARCHAR(20) DEFAULT 'Active',
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        LastLogin DATETIME,
        IsActive BIT DEFAULT 1
    );
    PRINT 'Table Users created successfully.';
END

-- ===========================================
-- 2. CREATE APPLICATIONS TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Applications')
BEGIN
    CREATE TABLE Applications (
        AppId INT PRIMARY KEY IDENTITY(1,1),
        Name NVARCHAR(100) NOT NULL,
        Type NVARCHAR(50),
        Status NVARCHAR(20) DEFAULT 'online',
        Icon NVARCHAR(50),
        Description NVARCHAR(500),
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME()))
    );
    PRINT 'Table Applications created successfully.';
END

-- ===========================================
-- 3. CREATE ACCOUNTS TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Accounts')
BEGIN
    CREATE TABLE Accounts (
        AccountId INT PRIMARY KEY IDENTITY(1,1),
        UserId INT NOT NULL,
        AppId INT NOT NULL,
        AccountUsername NVARCHAR(100),
        AccountPassword NVARCHAR(255),
        Email NVARCHAR(100),
        AccessLevel NVARCHAR(50),
        Status NVARCHAR(20) DEFAULT 'Active',
        Notes NVARCHAR(MAX),
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE,
        FOREIGN KEY (AppId) REFERENCES Applications(AppId) ON DELETE CASCADE
    );
    PRINT 'Table Accounts created successfully.';
END

-- ===========================================
-- 4. CREATE ASSET INVENTORY TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AssetInventory')
BEGIN
    CREATE TABLE AssetInventory (
        AssetId INT PRIMARY KEY IDENTITY(1,1),
        AssetCode NVARCHAR(100) NOT NULL UNIQUE,
        AssetName NVARCHAR(255) NOT NULL,
        Model NVARCHAR(255),
        SerialNumber NVARCHAR(100),
        Quantity INT NOT NULL DEFAULT 0,
        ImportInPeriod INT NOT NULL DEFAULT 0,
        ExportInPeriod INT NOT NULL DEFAULT 0,
        EndingBalance INT NOT NULL DEFAULT 0,
        NewQuantity INT NOT NULL DEFAULT 0,
        UsedQuantity INT NOT NULL DEFAULT 0,
        Unit NVARCHAR(50),
        Department NVARCHAR(100),
        Project NVARCHAR(150),
        Location NVARCHAR(150),
        Custodian NVARCHAR(100),
        Borrower NVARCHAR(255),
        ExportedBy NVARCHAR(100),
        PurchaseDate DATE NULL,
        PurchasePrice DECIMAL(18,2) NULL,
        Status NVARCHAR(30) NOT NULL DEFAULT 'in_use',
        Notes NVARCHAR(MAX),
        CreatedBy INT NULL,
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
    );
    PRINT 'Table AssetInventory created successfully.';
END

IF COL_LENGTH('dbo.AssetInventory', 'Borrower') IS NULL
BEGIN
    ALTER TABLE AssetInventory ADD Borrower NVARCHAR(255) NULL;
END

IF COL_LENGTH('dbo.AssetInventory', 'ExportedBy') IS NULL
BEGIN
    ALTER TABLE AssetInventory ADD ExportedBy NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.AssetInventory', 'NewQuantity') IS NULL
BEGIN
    ALTER TABLE AssetInventory ADD NewQuantity INT NOT NULL CONSTRAINT DF_AssetInventory_NewQuantity DEFAULT(0);
END

IF COL_LENGTH('dbo.AssetInventory', 'UsedQuantity') IS NULL
BEGIN
    ALTER TABLE AssetInventory ADD UsedQuantity INT NOT NULL CONSTRAINT DF_AssetInventory_UsedQuantity DEFAULT(0);
END

UPDATE AssetInventory
SET EndingBalance = ISNULL(EndingBalance, ISNULL(Quantity, 0));

UPDATE AssetInventory
SET UsedQuantity = CASE WHEN ISNULL(UsedQuantity, 0) < 0 THEN 0 ELSE ISNULL(UsedQuantity, 0) END;

UPDATE AssetInventory
SET NewQuantity = CASE
    WHEN ISNULL(NewQuantity, 0) < 0 THEN 0
    ELSE ISNULL(NewQuantity, 0)
END;

UPDATE AssetInventory
SET NewQuantity = CASE
        WHEN (ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)) < ISNULL(EndingBalance, 0)
            THEN ISNULL(NewQuantity, 0) + (ISNULL(EndingBalance, 0) - (ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)))
        WHEN (ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)) > ISNULL(EndingBalance, 0)
            THEN CASE
                WHEN ISNULL(NewQuantity, 0) >= ((ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)) - ISNULL(EndingBalance, 0))
                    THEN ISNULL(NewQuantity, 0) - ((ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)) - ISNULL(EndingBalance, 0))
                ELSE 0
            END
        ELSE ISNULL(NewQuantity, 0)
    END,
    UsedQuantity = CASE
        WHEN (ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)) > ISNULL(EndingBalance, 0)
            AND ISNULL(NewQuantity, 0) < ((ISNULL(NewQuantity, 0) + ISNULL(UsedQuantity, 0)) - ISNULL(EndingBalance, 0))
            THEN ISNULL(EndingBalance, 0)
        ELSE ISNULL(UsedQuantity, 0)
    END;

-- ===========================================
-- 5. CREATE CONSUMABLE INVENTORY TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'ConsumableInventory')
BEGIN
    CREATE TABLE ConsumableInventory (
        ConsumableId INT PRIMARY KEY IDENTITY(1,1),
        RequestMonth NVARCHAR(50) NULL,
        ConsumableCode NVARCHAR(100) NOT NULL UNIQUE,
        ConsumableName NVARCHAR(255) NOT NULL,
        Model NVARCHAR(255) NULL,
        Unit NVARCHAR(50) NULL,
        OpeningBalance INT NOT NULL DEFAULT 0,
        ImportInPeriod INT NOT NULL DEFAULT 0,
        ExportInPeriod INT NOT NULL DEFAULT 0,
        EndingBalance INT NOT NULL DEFAULT 0,
        ExportReason NVARCHAR(1000) NULL,
        CreatedBy INT NULL,
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
    );
    PRINT 'Table ConsumableInventory created successfully.';
END

IF COL_LENGTH('dbo.ConsumableInventory', 'RequestMonth') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD RequestMonth NVARCHAR(50) NULL;
END

IF COL_LENGTH('dbo.ConsumableInventory', 'Model') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD Model NVARCHAR(255) NULL;
END

IF COL_LENGTH('dbo.ConsumableInventory', 'Unit') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD Unit NVARCHAR(50) NULL;
END

IF COL_LENGTH('dbo.ConsumableInventory', 'OpeningBalance') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD OpeningBalance INT NOT NULL CONSTRAINT DF_ConsumableInventory_OpeningBalance DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableInventory', 'ImportInPeriod') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD ImportInPeriod INT NOT NULL CONSTRAINT DF_ConsumableInventory_ImportInPeriod DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableInventory', 'ExportInPeriod') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD ExportInPeriod INT NOT NULL CONSTRAINT DF_ConsumableInventory_ExportInPeriod DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableInventory', 'EndingBalance') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD EndingBalance INT NOT NULL CONSTRAINT DF_ConsumableInventory_EndingBalance DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableInventory', 'ExportReason') IS NULL
BEGIN
    ALTER TABLE ConsumableInventory ADD ExportReason NVARCHAR(1000) NULL;
END

-- ===========================================
-- 6. CREATE CONSUMABLE EXPORT HISTORY TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'ConsumableExportHistory')
BEGIN
    CREATE TABLE ConsumableExportHistory (
        ExportHistoryId INT PRIMARY KEY IDENTITY(1,1),
        ConsumableId INT NOT NULL,
        ConsumableCode NVARCHAR(100) NOT NULL,
        ConsumableName NVARCHAR(255) NOT NULL,
        Unit NVARCHAR(50) NULL,
        ExportQuantity INT NOT NULL DEFAULT 1,
        RecipientUserId INT NULL,
        RecipientName NVARCHAR(100) NULL,
        ProjectName NVARCHAR(150) NULL,
        ExportedByName NVARCHAR(100) NOT NULL,
        ExportNote NVARCHAR(1000) NULL,
        PreviousExportInPeriod INT NOT NULL DEFAULT 0,
        NextExportInPeriod INT NOT NULL DEFAULT 0,
        PreviousEndingBalance INT NOT NULL DEFAULT 0,
        NextEndingBalance INT NOT NULL DEFAULT 0,
        CreatedBy INT NULL,
        ExportedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (ConsumableId) REFERENCES ConsumableInventory(ConsumableId) ON DELETE CASCADE,
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
    );
    PRINT 'Table ConsumableExportHistory created successfully.';
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'ConsumableCode') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD ConsumableCode NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'ConsumableName') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD ConsumableName NVARCHAR(255) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'Unit') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD Unit NVARCHAR(50) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'ExportQuantity') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD ExportQuantity INT NOT NULL CONSTRAINT DF_ConsumableExportHistory_ExportQuantity DEFAULT(1);
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'RecipientName') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD RecipientName NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'RecipientUserId') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD RecipientUserId INT NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'RecipientName') IS NOT NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ALTER COLUMN RecipientName NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'ProjectName') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD ProjectName NVARCHAR(150) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'ExportedByName') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD ExportedByName NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'ExportNote') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD ExportNote NVARCHAR(1000) NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'PreviousExportInPeriod') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD PreviousExportInPeriod INT NOT NULL CONSTRAINT DF_ConsumableExportHistory_PreviousExportInPeriod DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'NextExportInPeriod') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD NextExportInPeriod INT NOT NULL CONSTRAINT DF_ConsumableExportHistory_NextExportInPeriod DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'PreviousEndingBalance') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD PreviousEndingBalance INT NOT NULL CONSTRAINT DF_ConsumableExportHistory_PreviousEndingBalance DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'NextEndingBalance') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD NextEndingBalance INT NOT NULL CONSTRAINT DF_ConsumableExportHistory_NextEndingBalance DEFAULT(0);
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'CreatedBy') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD CreatedBy INT NULL;
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'ExportedDate') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD ExportedDate DATETIME NOT NULL CONSTRAINT DF_ConsumableExportHistory_ExportedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME()));
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'CreatedDate') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD CreatedDate DATETIME NOT NULL CONSTRAINT DF_ConsumableExportHistory_CreatedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME()));
END

IF COL_LENGTH('dbo.ConsumableExportHistory', 'UpdatedDate') IS NULL
BEGIN
    ALTER TABLE ConsumableExportHistory ADD UpdatedDate DATETIME NOT NULL CONSTRAINT DF_ConsumableExportHistory_UpdatedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME()));
END

IF NOT EXISTS (
    SELECT 1
    FROM sys.foreign_key_columns fkc
    INNER JOIN sys.columns c
        ON c.object_id = fkc.parent_object_id
        AND c.column_id = fkc.parent_column_id
    WHERE fkc.parent_object_id = OBJECT_ID('dbo.ConsumableExportHistory')
      AND c.name = 'ConsumableId'
)
AND COL_LENGTH('dbo.ConsumableExportHistory', 'ConsumableId') IS NOT NULL
BEGIN
    ALTER TABLE ConsumableExportHistory
    ADD CONSTRAINT FK_ConsumableExportHistory_ConsumableId
    FOREIGN KEY (ConsumableId) REFERENCES ConsumableInventory(ConsumableId) ON DELETE CASCADE;
END

UPDATE exports
SET RecipientUserId = matchedUser.UserId
FROM ConsumableExportHistory exports
CROSS APPLY (
    SELECT TOP 1 users.UserId
    FROM Users users
    WHERE NULLIF(LTRIM(RTRIM(exports.ProjectName)), '') IS NULL
      AND (
          LOWER(LTRIM(RTRIM(ISNULL(users.FullName, '')))) = LOWER(LTRIM(RTRIM(ISNULL(exports.RecipientName, ''))))
          OR LOWER(LTRIM(RTRIM(ISNULL(users.Username, '')))) = LOWER(LTRIM(RTRIM(ISNULL(exports.RecipientName, ''))))
      )
    ORDER BY CASE
        WHEN LOWER(LTRIM(RTRIM(ISNULL(users.FullName, '')))) = LOWER(LTRIM(RTRIM(ISNULL(exports.RecipientName, '')))) THEN 0
        ELSE 1
    END,
    users.UserId
) matchedUser
WHERE exports.RecipientUserId IS NULL;

IF NOT EXISTS (
    SELECT 1
    FROM sys.foreign_key_columns fkc
    INNER JOIN sys.columns c
        ON c.object_id = fkc.parent_object_id
        AND c.column_id = fkc.parent_column_id
    WHERE fkc.parent_object_id = OBJECT_ID('dbo.ConsumableExportHistory')
      AND c.name = 'CreatedBy'
)
AND COL_LENGTH('dbo.ConsumableExportHistory', 'CreatedBy') IS NOT NULL
BEGIN
    ALTER TABLE ConsumableExportHistory
    ADD CONSTRAINT FK_ConsumableExportHistory_CreatedBy
    FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL;
END

-- ===========================================
-- 6B. CREATE CONSUMABLE RETURN HISTORY TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'ConsumableReturnHistory')
BEGIN
    CREATE TABLE ConsumableReturnHistory (
        ReturnHistoryId INT PRIMARY KEY IDENTITY(1,1),
        ExportHistoryId INT NOT NULL,
        ConsumableId INT NOT NULL,
        ReturnQuantity INT NOT NULL DEFAULT 1,
        ReturnedByName NVARCHAR(100) NOT NULL,
        ReturnNote NVARCHAR(1000) NULL,
        PreviousExportInPeriod INT NOT NULL DEFAULT 0,
        NextExportInPeriod INT NOT NULL DEFAULT 0,
        PreviousEndingBalance INT NOT NULL DEFAULT 0,
        NextEndingBalance INT NOT NULL DEFAULT 0,
        CreatedBy INT NULL,
        ReturnedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (ExportHistoryId) REFERENCES ConsumableExportHistory(ExportHistoryId) ON DELETE CASCADE,
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
    );
    PRINT 'Table ConsumableReturnHistory created successfully.';
END

-- ===========================================
-- 6C. CREATE CONSUMABLE BORROW REQUESTS TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'ConsumableBorrowRequests')
BEGIN
    CREATE TABLE ConsumableBorrowRequests (
        BorrowRequestId INT PRIMARY KEY IDENTITY(1,1),
        ConsumableId INT NOT NULL,
        RequestType NVARCHAR(20) NOT NULL DEFAULT 'borrow',
        BorrowerName NVARCHAR(100) NOT NULL,
        BorrowQuantity INT NOT NULL DEFAULT 1,
        Unit NVARCHAR(50) NULL,
        BorrowDate DATE NOT NULL DEFAULT (CAST(DATEADD(HOUR, 7, SYSUTCDATETIME()) AS DATE)),
        RequestStatus NVARCHAR(20) NOT NULL DEFAULT 'pending',
        RequestNote NVARCHAR(500) NULL,
        RejectReason NVARCHAR(1000) NULL,
        ExportHistoryId INT NULL,
        CreatedBy INT NULL,
        ProcessedBy INT NULL,
        ProcessedByName NVARCHAR(100) NULL,
        ProcessedDate DATETIME NULL,
        CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (ConsumableId) REFERENCES ConsumableInventory(ConsumableId) ON DELETE CASCADE,
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
    );
    PRINT 'Table ConsumableBorrowRequests created successfully.';
END

IF COL_LENGTH('dbo.ConsumableBorrowRequests', 'RequestType') IS NULL
BEGIN
    ALTER TABLE ConsumableBorrowRequests
    ADD RequestType NVARCHAR(20) NOT NULL CONSTRAINT DF_ConsumableBorrowRequests_RequestType DEFAULT('borrow');
END

UPDATE ConsumableBorrowRequests
SET RequestType = 'borrow'
WHERE RequestType IS NULL OR LTRIM(RTRIM(RequestType)) = '';

DECLARE @ConsumableBorrowProcessedByFk NVARCHAR(128);
SELECT TOP 1 @ConsumableBorrowProcessedByFk = fk.name
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN sys.columns c
    ON c.object_id = fkc.parent_object_id
    AND c.column_id = fkc.parent_column_id
WHERE fk.parent_object_id = OBJECT_ID('dbo.ConsumableBorrowRequests')
  AND c.name = 'ProcessedBy';

IF @ConsumableBorrowProcessedByFk IS NOT NULL
BEGIN
    DECLARE @DropConsumableBorrowProcessedByFkSql NVARCHAR(MAX) =
        N'ALTER TABLE ConsumableBorrowRequests DROP CONSTRAINT ' + QUOTENAME(@ConsumableBorrowProcessedByFk);
    EXEC sp_executesql @DropConsumableBorrowProcessedByFkSql;
END

-- ===========================================
-- 7. CREATE ASSET DEPARTMENTS TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AssetDepartments')
BEGIN
    CREATE TABLE AssetDepartments (
        DepartmentId INT PRIMARY KEY IDENTITY(1,1),
        DepartmentName NVARCHAR(100) NOT NULL,
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME()))
    );
    PRINT 'Table AssetDepartments created successfully.';
END

;WITH SourceDepartments AS (
    SELECT DISTINCT LTRIM(RTRIM(Department)) AS DepartmentName
    FROM AssetInventory
    WHERE Department IS NOT NULL
      AND LTRIM(RTRIM(Department)) <> ''
)
INSERT INTO AssetDepartments (DepartmentName)
SELECT source.DepartmentName
FROM SourceDepartments source
WHERE NOT EXISTS (
    SELECT 1
    FROM AssetDepartments target
    WHERE LOWER(LTRIM(RTRIM(target.DepartmentName))) = LOWER(source.DepartmentName)
);

-- ===========================================
-- 8. CREATE ASSET PROJECTS TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AssetProjects')
BEGIN
    CREATE TABLE AssetProjects (
        ProjectId INT PRIMARY KEY IDENTITY(1,1),
        ProjectName NVARCHAR(150) NOT NULL,
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME()))
    );
    PRINT 'Table AssetProjects created successfully.';
END

-- ===========================================
-- 9. CREATE ASSET BORROW REQUESTS TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AssetBorrowRequests')
BEGIN
    CREATE TABLE AssetBorrowRequests (
        BorrowId INT PRIMARY KEY IDENTITY(1,1),
        AssetId INT NOT NULL,
        RequestType NVARCHAR(20) NOT NULL DEFAULT 'borrow',
        RequestStatus NVARCHAR(20) NOT NULL DEFAULT 'pending',
        BorrowerName NVARCHAR(100) NOT NULL,
        BorrowQuantity INT NOT NULL DEFAULT 1,
        ReturnedQuantity INT NOT NULL DEFAULT 0,
        Unit NVARCHAR(50),
        BorrowDate DATE NOT NULL DEFAULT (CAST(DATEADD(HOUR, 7, SYSUTCDATETIME()) AS DATE)),
        RequestNote NVARCHAR(500) NULL,
        RejectReason NVARCHAR(1000) NULL,
        CreatedBy INT NULL,
        ProcessedBy INT NULL,
        ProcessedByName NVARCHAR(100) NULL,
        ProcessedDate DATETIME NULL,
        CreatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (AssetId) REFERENCES AssetInventory(AssetId) ON DELETE CASCADE,
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
    );
    PRINT 'Table AssetBorrowRequests created successfully.';
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'Unit') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD Unit NVARCHAR(50) NULL;
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'BorrowDate') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD BorrowDate DATE NOT NULL CONSTRAINT DF_AssetBorrowRequests_BorrowDate DEFAULT(CAST(DATEADD(HOUR, 7, SYSUTCDATETIME()) AS DATE));
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'UpdatedDate') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD UpdatedDate DATETIME NOT NULL CONSTRAINT DF_AssetBorrowRequests_UpdatedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME()));
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'RequestType') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD RequestType NVARCHAR(20) NOT NULL CONSTRAINT DF_AssetBorrowRequests_RequestType DEFAULT('borrow');
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'RequestStatus') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD RequestStatus NVARCHAR(20) NOT NULL CONSTRAINT DF_AssetBorrowRequests_RequestStatus DEFAULT('approved');
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'ReturnedQuantity') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD ReturnedQuantity INT NOT NULL CONSTRAINT DF_AssetBorrowRequests_ReturnedQuantity DEFAULT(0);
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'RequestNote') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD RequestNote NVARCHAR(500) NULL;
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'RejectReason') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD RejectReason NVARCHAR(1000) NULL;
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'ProcessedBy') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD ProcessedBy INT NULL;
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'ProcessedByName') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD ProcessedByName NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.AssetBorrowRequests', 'ProcessedDate') IS NULL
BEGIN
    ALTER TABLE AssetBorrowRequests ADD ProcessedDate DATETIME NULL;
END

UPDATE AssetBorrowRequests
SET RequestType = ISNULL(NULLIF(LTRIM(RTRIM(RequestType)), ''), 'borrow');

UPDATE AssetBorrowRequests
SET RequestStatus = ISNULL(NULLIF(LTRIM(RTRIM(RequestStatus)), ''), 'approved');

UPDATE AssetBorrowRequests
SET ReturnedQuantity = 0
WHERE ReturnedQuantity IS NULL OR ReturnedQuantity < 0;

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AssetBorrowRequestLinks')
BEGIN
    CREATE TABLE AssetBorrowRequestLinks (
        LinkId INT PRIMARY KEY IDENTITY(1,1),
        BorrowId INT NOT NULL,
        ReturnId INT NOT NULL,
        Quantity INT NOT NULL CONSTRAINT DF_AssetBorrowRequestLinks_Quantity DEFAULT(1),
        CreatedDate DATETIME NOT NULL CONSTRAINT DF_AssetBorrowRequestLinks_CreatedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (BorrowId) REFERENCES AssetBorrowRequests(BorrowId) ON DELETE NO ACTION,
        FOREIGN KEY (ReturnId) REFERENCES AssetBorrowRequests(BorrowId) ON DELETE NO ACTION
    );
END

IF OBJECT_ID('dbo.AssetBorrowRequestLinks', 'U') IS NOT NULL
BEGIN
    INSERT INTO AssetBorrowRequestLinks (BorrowId, ReturnId, Quantity)
    SELECT matchedBorrow.BorrowId,
           ret.BorrowId,
           CASE
               WHEN ISNULL(ret.BorrowQuantity, 0) <= 0 THEN 1
               WHEN ISNULL(ret.BorrowQuantity, 0) > ISNULL(matchedBorrow.BorrowQuantity, 0) THEN ISNULL(matchedBorrow.BorrowQuantity, 0)
               ELSE ISNULL(ret.BorrowQuantity, 0)
           END
    FROM AssetBorrowRequests ret
    CROSS APPLY (
        SELECT TOP 1 b.BorrowId, b.BorrowQuantity
        FROM AssetBorrowRequests b
        WHERE LOWER(LTRIM(RTRIM(ISNULL(b.RequestType, '')))) = 'borrow'
          AND LOWER(LTRIM(RTRIM(ISNULL(b.RequestStatus, '')))) IN ('approved', 'returned')
          AND b.AssetId = ret.AssetId
          AND (
                (ret.CreatedBy IS NOT NULL AND b.CreatedBy = ret.CreatedBy)
                OR LOWER(LTRIM(RTRIM(ISNULL(b.BorrowerName, '')))) = LOWER(LTRIM(RTRIM(ISNULL(ret.BorrowerName, ''))))
          )
          AND b.BorrowDate <= ret.BorrowDate
        ORDER BY b.BorrowDate DESC, b.CreatedDate DESC, b.BorrowId DESC
    ) matchedBorrow
    WHERE LOWER(LTRIM(RTRIM(ISNULL(ret.RequestType, '')))) = 'return'
      AND LOWER(LTRIM(RTRIM(ISNULL(ret.RequestStatus, '')))) IN ('pending', 'approved')
      AND NOT EXISTS (
            SELECT 1
            FROM AssetBorrowRequestLinks existed
            WHERE existed.ReturnId = ret.BorrowId
      )
      AND NOT EXISTS (
            SELECT 1
            FROM AssetBorrowRequestLinks duplicateLink
            WHERE duplicateLink.ReturnId = ret.BorrowId
              AND duplicateLink.BorrowId = matchedBorrow.BorrowId
      );

    UPDATE borrowRows
    SET ReturnedQuantity = CASE
            WHEN summary.ReturnedQuantity > ISNULL(borrowRows.BorrowQuantity, 0) THEN ISNULL(borrowRows.BorrowQuantity, 0)
            ELSE summary.ReturnedQuantity
        END,
        RequestStatus = CASE
            WHEN summary.ReturnedQuantity >= ISNULL(borrowRows.BorrowQuantity, 0)
                THEN 'returned'
            ELSE borrowRows.RequestStatus
        END,
        UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
    FROM AssetBorrowRequests borrowRows
    INNER JOIN (
        SELECT links.BorrowId, SUM(ISNULL(links.Quantity, 0)) AS ReturnedQuantity
        FROM AssetBorrowRequestLinks links
        INNER JOIN AssetBorrowRequests returns ON returns.BorrowId = links.ReturnId
        WHERE LOWER(LTRIM(RTRIM(ISNULL(returns.RequestStatus, '')))) = 'approved'
        GROUP BY links.BorrowId
    ) summary ON summary.BorrowId = borrowRows.BorrowId
    WHERE LOWER(LTRIM(RTRIM(ISNULL(borrowRows.RequestType, '')))) = 'borrow';
END

-- ===========================================
-- 10. CREATE ASSET EXPORT HISTORY TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AssetExportHistory')
BEGIN
    CREATE TABLE AssetExportHistory (
        ExportHistoryId INT PRIMARY KEY IDENTITY(1,1),
        AssetId INT NOT NULL,
        AssetCode NVARCHAR(100) NOT NULL,
        AssetName NVARCHAR(255) NOT NULL,
        ExportQuantity INT NOT NULL DEFAULT 1,
        ProjectName NVARCHAR(150) NULL,
        CustodianName NVARCHAR(100) NOT NULL,
        ExportedByName NVARCHAR(100) NOT NULL,
        ExportNote NVARCHAR(1000) NULL,
        CreatedBy INT NULL,
        ExportedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (AssetId) REFERENCES AssetInventory(AssetId) ON DELETE CASCADE
    );
    PRINT 'Table AssetExportHistory created successfully.';
END

IF COL_LENGTH('dbo.AssetExportHistory', 'AssetCode') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD AssetCode NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.AssetExportHistory', 'AssetName') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD AssetName NVARCHAR(255) NULL;
END

IF COL_LENGTH('dbo.AssetExportHistory', 'ExportQuantity') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD ExportQuantity INT NOT NULL CONSTRAINT DF_AssetExportHistory_ExportQuantity DEFAULT(1);
END

IF COL_LENGTH('dbo.AssetExportHistory', 'ProjectName') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD ProjectName NVARCHAR(150) NULL;
END

IF COL_LENGTH('dbo.AssetExportHistory', 'CustodianName') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD CustodianName NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.AssetExportHistory', 'ExportedByName') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD ExportedByName NVARCHAR(100) NULL;
END

IF COL_LENGTH('dbo.AssetExportHistory', 'ExportNote') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD ExportNote NVARCHAR(1000) NULL;
END

IF COL_LENGTH('dbo.AssetExportHistory', 'CreatedBy') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD CreatedBy INT NULL;
END

IF COL_LENGTH('dbo.AssetExportHistory', 'ExportedDate') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD ExportedDate DATETIME NOT NULL CONSTRAINT DF_AssetExportHistory_ExportedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME()));
END

IF COL_LENGTH('dbo.AssetExportHistory', 'CreatedDate') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD CreatedDate DATETIME NOT NULL CONSTRAINT DF_AssetExportHistory_CreatedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME()));
END

IF COL_LENGTH('dbo.AssetExportHistory', 'UpdatedDate') IS NULL
BEGIN
    ALTER TABLE AssetExportHistory ADD UpdatedDate DATETIME NOT NULL CONSTRAINT DF_AssetExportHistory_UpdatedDate DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME()));
END

IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_AssetExportHistory_CreatedBy')
   AND COL_LENGTH('dbo.AssetExportHistory', 'CreatedBy') IS NOT NULL
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM sys.foreign_key_columns fkc
        INNER JOIN sys.columns c
            ON c.object_id = fkc.parent_object_id
            AND c.column_id = fkc.parent_column_id
        WHERE fkc.parent_object_id = OBJECT_ID('dbo.AssetExportHistory')
          AND c.name = 'CreatedBy'
    )
    BEGIN
        ALTER TABLE AssetExportHistory
        ADD CONSTRAINT FK_AssetExportHistory_CreatedBy
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL;
    END
END

-- ===========================================
-- 11. CREATE ASSET DAMAGE/DISPOSAL HISTORY TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AssetDamageDisposalHistory')
BEGIN
    CREATE TABLE AssetDamageDisposalHistory (
        DamageHistoryId INT PRIMARY KEY IDENTITY(1,1),
        AssetId INT NOT NULL,
        AssetCode NVARCHAR(100) NOT NULL,
        AssetName NVARCHAR(255) NOT NULL,
        ActionType NVARCHAR(20) NOT NULL,
        ActionLabel NVARCHAR(50) NOT NULL,
        ActionQuantity INT NOT NULL DEFAULT 1,
        Unit NVARCHAR(50) NULL,
        PreviousQuantity INT NOT NULL DEFAULT 0,
        NextQuantity INT NOT NULL DEFAULT 0,
        PreviousImportInPeriod INT NOT NULL DEFAULT 0,
        NextImportInPeriod INT NOT NULL DEFAULT 0,
        PreviousExportInPeriod INT NOT NULL DEFAULT 0,
        NextExportInPeriod INT NOT NULL DEFAULT 0,
        PreviousEndingBalance INT NOT NULL DEFAULT 0,
        NextEndingBalance INT NOT NULL DEFAULT 0,
        PreviousNewQuantity INT NOT NULL DEFAULT 0,
        NextNewQuantity INT NOT NULL DEFAULT 0,
        PreviousUsedQuantity INT NOT NULL DEFAULT 0,
        NextUsedQuantity INT NOT NULL DEFAULT 0,
        ActionNote NVARCHAR(1000) NULL,
        CreatedBy INT NULL,
        CreatedByName NVARCHAR(100) NULL,
        ActionDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (AssetId) REFERENCES AssetInventory(AssetId) ON DELETE CASCADE,
        FOREIGN KEY (CreatedBy) REFERENCES Users(UserId) ON DELETE SET NULL
    );
    PRINT 'Table AssetDamageDisposalHistory created successfully.';
END

-- ===========================================
-- 12. CREATE AUDIT LOG TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog')
BEGIN
    CREATE TABLE AuditLog (
        LogId INT PRIMARY KEY IDENTITY(1,1),
        UserId INT,
        Action NVARCHAR(50),
        TableName NVARCHAR(50),
        RecordId INT,
        OldValue NVARCHAR(MAX),
        NewValue NVARCHAR(MAX),
        Timestamp DATETIME DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
        FOREIGN KEY (UserId) REFERENCES Users(UserId)
    );
    PRINT 'Table AuditLog created successfully.';
END

-- ===========================================
-- 13. CREATE INDEXES
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_Users_Username')
BEGIN
    CREATE INDEX IX_Users_Username ON Users(Username);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_Accounts_UserId')
BEGIN
    CREATE INDEX IX_Accounts_UserId ON Accounts(UserId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_Accounts_AppId')
BEGIN
    CREATE INDEX IX_Accounts_AppId ON Accounts(AppId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetInventory_AssetCode')
BEGIN
    CREATE INDEX IX_AssetInventory_AssetCode ON AssetInventory(AssetCode);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetInventory_Status')
BEGIN
    CREATE INDEX IX_AssetInventory_Status ON AssetInventory(Status);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetInventory_Department')
BEGIN
    CREATE INDEX IX_AssetInventory_Department ON AssetInventory(Department);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableInventory_ConsumableCode')
BEGIN
    CREATE INDEX IX_ConsumableInventory_ConsumableCode ON ConsumableInventory(ConsumableCode);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableInventory_RequestMonth')
BEGIN
    CREATE INDEX IX_ConsumableInventory_RequestMonth ON ConsumableInventory(RequestMonth);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableInventory_EndingBalance')
BEGIN
    CREATE INDEX IX_ConsumableInventory_EndingBalance ON ConsumableInventory(EndingBalance);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableExportHistory_ConsumableId')
BEGIN
    CREATE INDEX IX_ConsumableExportHistory_ConsumableId ON ConsumableExportHistory(ConsumableId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableExportHistory_ExportedDate')
BEGIN
    CREATE INDEX IX_ConsumableExportHistory_ExportedDate ON ConsumableExportHistory(ExportedDate DESC);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableExportHistory_RecipientUserId')
BEGIN
    CREATE INDEX IX_ConsumableExportHistory_RecipientUserId ON ConsumableExportHistory(RecipientUserId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableReturnHistory_ExportHistoryId')
BEGIN
    CREATE INDEX IX_ConsumableReturnHistory_ExportHistoryId ON ConsumableReturnHistory(ExportHistoryId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableReturnHistory_ConsumableId')
BEGIN
    CREATE INDEX IX_ConsumableReturnHistory_ConsumableId ON ConsumableReturnHistory(ConsumableId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableReturnHistory_ReturnedDate')
BEGIN
    CREATE INDEX IX_ConsumableReturnHistory_ReturnedDate ON ConsumableReturnHistory(ReturnedDate DESC);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableBorrowRequests_ConsumableId')
BEGIN
    CREATE INDEX IX_ConsumableBorrowRequests_ConsumableId ON ConsumableBorrowRequests(ConsumableId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableBorrowRequests_CreatedBy')
BEGIN
    CREATE INDEX IX_ConsumableBorrowRequests_CreatedBy ON ConsumableBorrowRequests(CreatedBy);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableBorrowRequests_RequestStatus')
BEGIN
    CREATE INDEX IX_ConsumableBorrowRequests_RequestStatus ON ConsumableBorrowRequests(RequestStatus);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableBorrowRequests_CreatedDate')
BEGIN
    CREATE INDEX IX_ConsumableBorrowRequests_CreatedDate ON ConsumableBorrowRequests(CreatedDate DESC);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableBorrowRequests_RequestType')
BEGIN
    CREATE INDEX IX_ConsumableBorrowRequests_RequestType ON ConsumableBorrowRequests(RequestType);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_ConsumableBorrowRequests_ExportHistoryId')
BEGIN
    CREATE INDEX IX_ConsumableBorrowRequests_ExportHistoryId ON ConsumableBorrowRequests(ExportHistoryId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'UX_AssetDepartments_DepartmentName')
BEGIN
    CREATE UNIQUE INDEX UX_AssetDepartments_DepartmentName ON AssetDepartments(DepartmentName);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'UX_AssetProjects_ProjectName')
BEGIN
    CREATE UNIQUE INDEX UX_AssetProjects_ProjectName ON AssetProjects(ProjectName);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetBorrowRequests_AssetId')
BEGIN
    CREATE INDEX IX_AssetBorrowRequests_AssetId ON AssetBorrowRequests(AssetId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetBorrowRequests_BorrowDate')
BEGIN
    CREATE INDEX IX_AssetBorrowRequests_BorrowDate ON AssetBorrowRequests(BorrowDate DESC);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetBorrowRequests_RequestStatus')
BEGIN
    CREATE INDEX IX_AssetBorrowRequests_RequestStatus ON AssetBorrowRequests(RequestStatus);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetBorrowRequests_RequestType')
BEGIN
    CREATE INDEX IX_AssetBorrowRequests_RequestType ON AssetBorrowRequests(RequestType);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetBorrowRequestLinks_BorrowId')
BEGIN
    CREATE INDEX IX_AssetBorrowRequestLinks_BorrowId ON AssetBorrowRequestLinks(BorrowId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetBorrowRequestLinks_ReturnId')
BEGIN
    CREATE INDEX IX_AssetBorrowRequestLinks_ReturnId ON AssetBorrowRequestLinks(ReturnId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'UX_AssetBorrowRequestLinks_BorrowReturn')
BEGIN
    CREATE UNIQUE INDEX UX_AssetBorrowRequestLinks_BorrowReturn ON AssetBorrowRequestLinks(BorrowId, ReturnId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetExportHistory_AssetId')
BEGIN
    CREATE INDEX IX_AssetExportHistory_AssetId ON AssetExportHistory(AssetId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetExportHistory_ExportedDate')
BEGIN
    CREATE INDEX IX_AssetExportHistory_ExportedDate ON AssetExportHistory(ExportedDate DESC);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetDamageDisposalHistory_AssetId')
BEGIN
    CREATE INDEX IX_AssetDamageDisposalHistory_AssetId ON AssetDamageDisposalHistory(AssetId);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetDamageDisposalHistory_ActionDate')
BEGIN
    CREATE INDEX IX_AssetDamageDisposalHistory_ActionDate ON AssetDamageDisposalHistory(ActionDate DESC);
END

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_AssetDamageDisposalHistory_ActionType')
BEGIN
    CREATE INDEX IX_AssetDamageDisposalHistory_ActionType ON AssetDamageDisposalHistory(ActionType);
END

PRINT 'Indexes created successfully.';

-- ===========================================
-- 12. INSERT INITIAL DATA
-- ===========================================

-- Check if admin user exists
IF NOT EXISTS (SELECT * FROM Users WHERE Username = 'admin')
BEGIN
    INSERT INTO Users (Username, Password, Email, FullName, Role, Status, IsActive)
    VALUES ('admin', 'admin', 'admin@accmanager.local', 'Administrator', 'admin', 'Active', 1);
    PRINT 'Admin user created: Username=admin, Password=[REDACTED]
END

-- Insert sample applications
IF (SELECT COUNT(*) FROM Applications) = 0
BEGIN
    INSERT INTO Applications (Name, Type, Status, Icon, Description)
    VALUES 
        ('AWS', 'Cloud', 'online', 'cloud', 'Amazon Web Services - Cloud Computing'),
        ('GitHub', 'VCS', 'online', 'code', 'GitHub - Version Control System'),
        ('Google Workspace', 'Collaboration', 'online', 'mail', 'Google Workspace - Email and Collaboration'),
        ('Nginx Proxy', 'Infra', 'offline', 'dns', 'Nginx - Web Server and Reverse Proxy');
    PRINT 'Sample applications inserted successfully.';
END

-- ===========================================
-- 12. DISPLAY DATABASE INFORMATION
-- ===========================================
PRINT '';
PRINT '========================================';
PRINT 'DATABASE SETUP COMPLETED SUCCESSFULLY';
PRINT '========================================';
PRINT '';
PRINT 'Database Name: AccManager';
PRINT '';
PRINT 'Tables created:';
SELECT '  - ' + name AS TableName FROM sys.tables ORDER BY name;
PRINT '';
PRINT 'Users in system:';
SELECT '  Username: ' + Username + ' | Role: ' + Role + ' | Status: ' + Status AS UserInfo FROM Users;
PRINT '';
PRINT 'Applications available:';
SELECT '  - ' + Name + ' (' + Type + ') - ' + Status AS AppInfo FROM Applications ORDER BY Name;
PRINT '';
PRINT 'Login Credentials:';
PRINT '  Username: admin';
PRINT '  Password: [REDACTED]
PRINT '  Role: admin';
PRINT '';
PRINT '========================================';
