-- Create the database
CREATE DATABASE TestDUTASJobSchedule;
GO

USE TestDUTASJobSchedule;
GO

-- Create the main control table
CREATE TABLE dbo.JobControl (
    JobID INT IDENTITY(1,1) PRIMARY KEY,
    JobName VARCHAR(50) NOT NULL UNIQUE,
    ScheduledStartTime TIME NOT NULL,
    SchedulerAction VARCHAR(10) NOT NULL CHECK (SchedulerAction IN ('CONTINUE', 'STOP')),
    IsActive BIT DEFAULT 1,
    CreatedDate DATETIME DEFAULT GETDATE(),
	Frequency VARCHAR(20) NOT NULL
);
GO

-- Create job dependencies table
CREATE TABLE dbo.JobDependencies (
    DependencyID INT IDENTITY(1,1) PRIMARY KEY,
    JobName VARCHAR(50) NOT NULL,
    PredecessorJobName VARCHAR(50) NULL,
    FOREIGN KEY (JobName) REFERENCES dbo.JobControl(JobName)
);
GO

-- Create execution history table
CREATE TABLE dbo.JobExecutionHistory (
    ExecutionID INT IDENTITY(1,1) PRIMARY KEY,
    JobName VARCHAR(50) NOT NULL,
    RunDate DATE NOT NULL,
    ScheduledStartTime TIME NOT NULL,
    ActualStartTime DATETIME NULL,
    ActualEndTime DATETIME NULL,
    Status VARCHAR(20) DEFAULT 'Pending' CHECK (Status IN ('Pending', 'Running', 'Success', 'Failed', 'ForceComplete')),
    ErrorMessage VARCHAR(MAX) NULL,
    OverrideFlag BIT DEFAULT 0,
    OverrideBy VARCHAR(100) NULL,
    OverrideDate DATETIME NULL
);
GO

-- Create holidays table
CREATE TABLE dbo.FederalHolidays (
    HolidayID INT IDENTITY(1,1) PRIMARY KEY,
    HolidayDate DATE NOT NULL UNIQUE,
    HolidayName VARCHAR(100) NOT NULL,
    Year INT NOT NULL
);
GO

-- Create Exit Code table for PowerShell Script
CREATE TABLE dbo.JobExitCodes
(
    JobExecutionID INT IDENTITY(1,1) PRIMARY KEY,  -- unique ID per execution
    JobName NVARCHAR(128) NOT NULL,               -- job name
    RunDate DATE NOT NULL,                         -- date of execution
    ExitCode INT NOT NULL,                         -- exit code from job
    RecordedTime DATETIME NOT NULL DEFAULT GETDATE() -- timestamp of execution
);
GO
