-- Create Table
IF OBJECT_ID(N'[dbo].[Prj_T_Task]', N'U') IS NULL
BEGIN
    CREATE TABLE [dbo].[Prj_T_Task] (
        [Id]                   UNIQUEIDENTIFIER NOT NULL CONSTRAINT [PK_Prj_T_Task] PRIMARY KEY,
        [TenantId]             UNIQUEIDENTIFIER NULL,
        [Name]                 NVARCHAR(300)    NOT NULL,
        [MilestoneId]          UNIQUEIDENTIFIER NULL,
        [AssigneeIds]          NVARCHAR(1000)   NULL,
        [TagIds]               NVARCHAR(1000)   NULL,
        [CustomerId]           UNIQUEIDENTIFIER NULL,
        [CustomerContact]      NVARCHAR(200)    NULL,
        [SalesOrderLine]       NVARCHAR(300)    NULL,
        [PlannedHours]         DECIMAL(18, 2)   NULL,
        [ProgressPercent]      DECIMAL(18, 2)   NULL,
        [Status]               NVARCHAR(50)     NOT NULL CONSTRAINT [DF_Prj_T_Task_Status] DEFAULT (N'Taslak'),
        [PlannedStartDate]     DATETIME2        NULL,
        [PlannedEndDate]       DATETIME2        NULL,
        [IsFavorite]           BIT              NOT NULL CONSTRAINT [DF_Prj_T_Task_IsFavorite] DEFAULT (0),
        [ParentTaskId]         UNIQUEIDENTIFIER NULL,
        [Description]          NVARCHAR(MAX)    NULL,
        [CreationTime]         DATETIME2        NOT NULL CONSTRAINT [DF_Prj_T_Task_CreationTime] DEFAULT (GETUTCDATE()),
        [CreatorId]            UNIQUEIDENTIFIER NULL,
        [LastModificationTime] DATETIME2        NULL,
        [LastModifierId]       UNIQUEIDENTIFIER NULL,
        [IsDeleted]            BIT              NOT NULL CONSTRAINT [DF_Prj_T_Task_IsDeleted] DEFAULT (0),
        [DeletionTime]         DATETIME2        NULL,
        [DeleterId]            UNIQUEIDENTIFIER NULL
    );
END
GO

IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = N'FK_Prj_T_Task_Milestone')
    ALTER TABLE [dbo].[Prj_T_Task] ADD CONSTRAINT [FK_Prj_T_Task_Milestone]
        FOREIGN KEY ([MilestoneId]) REFERENCES [dbo].[Prj_T_Milestone] ([Id]);
GO

IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = N'FK_Prj_T_Task_Customer')
    ALTER TABLE [dbo].[Prj_T_Task] ADD CONSTRAINT [FK_Prj_T_Task_Customer]
        FOREIGN KEY ([CustomerId]) REFERENCES [dbo].[Prj_T_Customer] ([Id]);
GO

IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = N'FK_Prj_T_Task_ParentTask')
    ALTER TABLE [dbo].[Prj_T_Task] ADD CONSTRAINT [FK_Prj_T_Task_ParentTask]
        FOREIGN KEY ([ParentTaskId]) REFERENCES [dbo].[Prj_T_Task] ([Id]);
GO

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_Prj_T_Task_TenantId_Status' AND object_id = OBJECT_ID(N'[dbo].[Prj_T_Task]'))
    CREATE INDEX [IX_Prj_T_Task_TenantId_Status] ON [dbo].[Prj_T_Task] ([TenantId] ASC, [Status] ASC);
GO

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_Prj_T_Task_ParentTaskId' AND object_id = OBJECT_ID(N'[dbo].[Prj_T_Task]'))
    CREATE INDEX [IX_Prj_T_Task_ParentTaskId] ON [dbo].[Prj_T_Task] ([ParentTaskId] ASC);
GO
