-- V2__init_projects_wbs.sql (MySQL)
-- Projects, WBS versions, WBS nodes, Canonical WBS

CREATE TABLE projects (
    id              BIGINT AUTO_INCREMENT PRIMARY KEY,
    project_code    VARCHAR(50)  NOT NULL UNIQUE,
    name            VARCHAR(255) NOT NULL,
    description     VARCHAR(1000) CHARACTER SET utf8mb4,
    project_type    VARCHAR(20) NOT NULL,
    status          VARCHAR(20) DEFAULT 'ACTIVE',
    start_date      DATE,
    end_date        DATE,
    pm_user_id      BIGINT,
    created_at      DATETIME DEFAULT NOW(),
    updated_at      DATETIME,
    CONSTRAINT fk_projects_pm FOREIGN KEY (pm_user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- user_roles FK to projects (deferred from V1 because projects did not exist yet)
ALTER TABLE user_roles
    ADD CONSTRAINT fk_user_roles_project FOREIGN KEY (project_id) REFERENCES projects(id);

CREATE TABLE wbs_versions (
    id              BIGINT AUTO_INCREMENT PRIMARY KEY,
    project_id      BIGINT NOT NULL,
    version_number  INT NOT NULL,
    effective_date  DATE NOT NULL,
    source_type     VARCHAR(20) DEFAULT 'P6_UPLOAD',
    source_filename VARCHAR(500),
    description     VARCHAR(500) CHARACTER SET utf8mb4,
    status          VARCHAR(20) DEFAULT 'DRAFT',
    uploaded_by     BIGINT,
    created_at      DATETIME DEFAULT NOW(),
    UNIQUE (project_id, version_number),
    CONSTRAINT fk_wbs_ver_project FOREIGN KEY (project_id) REFERENCES projects(id),
    CONSTRAINT fk_wbs_ver_uploader FOREIGN KEY (uploaded_by) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE wbs_nodes (
    id              BIGINT AUTO_INCREMENT PRIMARY KEY,
    wbs_version_id  BIGINT NOT NULL,
    parent_id       BIGINT NULL,
    wbs_code        VARCHAR(100) NOT NULL,
    level           INT NOT NULL,
    name            VARCHAR(500) CHARACTER SET utf8mb4 NOT NULL,
    discipline      VARCHAR(50),
    planned_hours   DECIMAL(10,2),
    sort_order      INT DEFAULT 0,
    is_leaf         TINYINT(1) DEFAULT 0,
    UNIQUE (wbs_version_id, wbs_code),
    CONSTRAINT fk_wbs_node_version FOREIGN KEY (wbs_version_id) REFERENCES wbs_versions(id),
    CONSTRAINT fk_wbs_node_parent FOREIGN KEY (parent_id) REFERENCES wbs_nodes(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE canonical_wbs (
    id              BIGINT AUTO_INCREMENT PRIMARY KEY,
    project_id      BIGINT NOT NULL,
    wbs_code        VARCHAR(100) NOT NULL,
    level           INT NOT NULL,
    name            VARCHAR(500) CHARACTER SET utf8mb4 NOT NULL,
    parent_code     VARCHAR(100),
    discipline      VARCHAR(50),
    is_active       TINYINT(1) DEFAULT 1,
    mapped_p6_code  VARCHAR(100),
    created_at      DATETIME DEFAULT NOW(),
    UNIQUE (project_id, wbs_code),
    CONSTRAINT fk_canonical_wbs_project FOREIGN KEY (project_id) REFERENCES projects(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
