-- Migration 006: mapping user ke mcu_project (many-to-many)

CREATE TABLE IF NOT EXISTS dashboard_user_project (
    UserProj_ID        INT AUTO_INCREMENT PRIMARY KEY,
    UserProj_UserID    INT NOT NULL,        -- dashboard_user.User_ID
    UserProj_McuID     INT NOT NULL,        -- mcu_project.Mcu_ProjectMcuID
    UserProj_IsActive  CHAR(1) DEFAULT 'Y',
    UserProj_CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
    UserProj_UpdatedAt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_user_mcu (UserProj_UserID, UserProj_McuID),
    INDEX idx_user_id (UserProj_UserID),
    INDEX idx_mcu_id (UserProj_McuID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- ============================================================
-- sp_assign_user_project
-- Assign satu mcu_project ke satu user (idempotent).
-- Parameter:
--   p_username  VARCHAR(50)  -- username di dashboard_user
--   p_mcu_id    INT          -- Mcu_ProjectMcuID di mcu_project
-- ============================================================
DROP PROCEDURE IF EXISTS sp_assign_user_project;

DELIMITER $$

CREATE PROCEDURE sp_assign_user_project(
    IN p_username VARCHAR(50),
    IN p_mcu_id   INT
)
BEGIN
    DECLARE v_user_id INT;

    -- Cari user
    SELECT User_ID INTO v_user_id
    FROM dashboard_user
    WHERE User_Username = p_username AND User_IsActive = 'Y'
    LIMIT 1;

    IF v_user_id IS NULL THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'User tidak ditemukan atau tidak aktif';
    END IF;

    -- Validasi mcu_project ada
    IF NOT EXISTS (
        SELECT 1 FROM mcu_project WHERE Mcu_ProjectMcuID = p_mcu_id
    ) THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'mcu_id tidak ditemukan di mcu_project';
    END IF;

    INSERT INTO dashboard_user_project (UserProj_UserID, UserProj_McuID, UserProj_IsActive)
    VALUES (v_user_id, p_mcu_id, 'Y')
    ON DUPLICATE KEY UPDATE
        UserProj_IsActive  = 'Y',
        UserProj_UpdatedAt = NOW();

END $$

DELIMITER ;


-- ============================================================
-- sp_remove_user_project
-- Cabut akses satu mcu_project dari user (soft delete).
-- Parameter:
--   p_username  VARCHAR(50)
--   p_mcu_id    INT
-- ============================================================
DROP PROCEDURE IF EXISTS sp_remove_user_project;

DELIMITER $$

CREATE PROCEDURE sp_remove_user_project(
    IN p_username VARCHAR(50),
    IN p_mcu_id   INT
)
BEGIN
    DECLARE v_user_id INT;

    SELECT User_ID INTO v_user_id
    FROM dashboard_user
    WHERE User_Username = p_username
    LIMIT 1;

    IF v_user_id IS NULL THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = 'User tidak ditemukan';
    END IF;

    UPDATE dashboard_user_project
    SET    UserProj_IsActive  = 'N',
           UserProj_UpdatedAt = NOW()
    WHERE  UserProj_UserID = v_user_id
      AND  UserProj_McuID  = p_mcu_id;

END $$

DELIMITER ;
