-- V1__init_users.sql (MySQL)
-- Converted from MSSQL DDL in 02-database-schema.md

CREATE TABLE users (
    id              BIGINT AUTO_INCREMENT PRIMARY KEY,
    employee_id     VARCHAR(50)  NOT NULL UNIQUE,
    email           VARCHAR(255) NOT NULL UNIQUE,
    username        VARCHAR(100) NOT NULL,
    full_name       VARCHAR(255),
    hashed_password VARCHAR(255),
    department      VARCHAR(100),
    discipline      VARCHAR(100),
    position_title  VARCHAR(100),
    location        VARCHAR(50),
    employment_type VARCHAR(20) DEFAULT 'INTERNAL',
    is_active       TINYINT(1) DEFAULT 1,
    is_locked       TINYINT(1) DEFAULT 0,
    failed_attempts INT DEFAULT 0,
    last_login_at   DATETIME,
    password_changed_at DATETIME,
    azure_oid       VARCHAR(255),
    mfa_enabled     TINYINT(1) DEFAULT 0,
    created_at      DATETIME DEFAULT NOW(),
    updated_at      DATETIME,
    created_by      BIGINT,
    updated_by      BIGINT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE roles (
    id          BIGINT AUTO_INCREMENT PRIMARY KEY,
    code        VARCHAR(20)  NOT NULL UNIQUE,
    name        VARCHAR(100) NOT NULL,
    description VARCHAR(500),
    level       INT DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE user_roles (
    id         BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id    BIGINT NOT NULL,
    role_id    BIGINT NOT NULL,
    project_id BIGINT NULL,
    granted_at DATETIME DEFAULT NOW(),
    granted_by BIGINT,
    UNIQUE (user_id, role_id, project_id),
    CONSTRAINT fk_user_roles_user FOREIGN KEY (user_id) REFERENCES users(id),
    CONSTRAINT fk_user_roles_role FOREIGN KEY (role_id) REFERENCES roles(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Seed roles
INSERT INTO roles (code, name, level) VALUES
    ('SA',   'System Administrator',   100),
    ('PM',   'Project Manager',         80),
    ('PCM',  'Project Control Manager', 70),
    ('PTK',  'Project Timekeeper',      60),
    ('DL',   'Discipline Lead',         50),
    ('USER', 'General User',            10);
