-- V4__init_timesheets.sql (MySQL)
-- Timesheets, timesheet entries, timesheet uploads

CREATE TABLE timesheets (
    id              BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id         BIGINT NOT NULL,
    week_start_date DATE NOT NULL,
    week_end_date   DATE NOT NULL,
    status          VARCHAR(20) DEFAULT 'DRAFT',
    total_hours     DECIMAL(10,2) DEFAULT 0,
    submitted_at    DATETIME,
    created_at      DATETIME DEFAULT NOW(),
    updated_at      DATETIME,
    UNIQUE (user_id, week_start_date),
    CONSTRAINT fk_ts_user FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE timesheet_entries (
    id               BIGINT AUTO_INCREMENT PRIMARY KEY,
    timesheet_id     BIGINT NOT NULL,
    entry_type       VARCHAR(20) NOT NULL,
    entry_date       DATE NOT NULL,
    hours            DECIMAL(5,2) NOT NULL DEFAULT 0,
    np_category      VARCHAR(100),
    other_project_id BIGINT NULL,
    other_category   VARCHAR(100),
    epc_project_id   BIGINT NULL,
    canonical_wbs_id BIGINT NULL,
    teal_entry_id    BIGINT NULL,
    revision_number  INT DEFAULT 1,
    remark           VARCHAR(500) CHARACTER SET utf8mb4,
    created_at       DATETIME DEFAULT NOW(),
    updated_at       DATETIME,
    CONSTRAINT chk_hours CHECK (hours >= 0 AND hours <= 24),
    CONSTRAINT fk_tse_timesheet FOREIGN KEY (timesheet_id) REFERENCES timesheets(id),
    CONSTRAINT fk_tse_other_proj FOREIGN KEY (other_project_id) REFERENCES projects(id),
    CONSTRAINT fk_tse_epc_proj FOREIGN KEY (epc_project_id) REFERENCES projects(id),
    CONSTRAINT fk_tse_cwbs FOREIGN KEY (canonical_wbs_id) REFERENCES canonical_wbs(id),
    CONSTRAINT fk_tse_teal FOREIGN KEY (teal_entry_id) REFERENCES teal_entries(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE INDEX idx_ts_entries_date ON timesheet_entries(entry_date);
CREATE INDEX idx_ts_entries_type ON timesheet_entries(entry_type);

CREATE TABLE timesheet_uploads (
    id           BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id      BIGINT NOT NULL,
    filename     VARCHAR(500),
    file_path    VARCHAR(1000),
    total_rows   INT,
    success_rows INT,
    error_rows   INT,
    error_log    TEXT CHARACTER SET utf8mb4,
    status       VARCHAR(20),
    created_at   DATETIME DEFAULT NOW(),
    CONSTRAINT fk_tsu_user FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
