-- V5__init_approvals.sql (MySQL)
-- Approvals, approval lines, approval comments

CREATE TABLE approvals (
    id           BIGINT AUTO_INCREMENT PRIMARY KEY,
    timesheet_id BIGINT NOT NULL,
    requester_id BIGINT NOT NULL,
    project_id   BIGINT,
    status       VARCHAR(20) DEFAULT 'PENDING',
    submitted_at DATETIME DEFAULT NOW(),
    completed_at DATETIME,
    UNIQUE (timesheet_id),
    CONSTRAINT fk_appr_timesheet FOREIGN KEY (timesheet_id) REFERENCES timesheets(id),
    CONSTRAINT fk_appr_requester FOREIGN KEY (requester_id) REFERENCES users(id),
    CONSTRAINT fk_appr_project FOREIGN KEY (project_id) REFERENCES projects(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE approval_lines (
    id             BIGINT AUTO_INCREMENT PRIMARY KEY,
    approval_id    BIGINT NOT NULL,
    approver_id    BIGINT NOT NULL,
    approval_order INT NOT NULL,
    role_code      VARCHAR(20),
    status         VARCHAR(20) DEFAULT 'PENDING',
    acted_at       DATETIME,
    created_at     DATETIME DEFAULT NOW(),
    CONSTRAINT fk_aline_approval FOREIGN KEY (approval_id) REFERENCES approvals(id),
    CONSTRAINT fk_aline_approver FOREIGN KEY (approver_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE approval_comments (
    id          BIGINT AUTO_INCREMENT PRIMARY KEY,
    approval_id BIGINT NOT NULL,
    user_id     BIGINT NOT NULL,
    comment     VARCHAR(2000) CHARACTER SET utf8mb4,
    action      VARCHAR(20),
    created_at  DATETIME DEFAULT NOW(),
    CONSTRAINT fk_acomm_approval FOREIGN KEY (approval_id) REFERENCES approvals(id),
    CONSTRAINT fk_acomm_user FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
