CREATE TABLE IF NOT EXISTS installer_actions (
    slug VARCHAR(100) NOT NULL PRIMARY KEY,
    display_name VARCHAR(255) NOT NULL,
    sort_order INT UNSIGNED NOT NULL DEFAULT 0,
    enabled BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
    updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
        ON UPDATE CURRENT_TIMESTAMP(6)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS authorization_actions (
    authorization_id BIGINT UNSIGNED NOT NULL,
    action_slug VARCHAR(100) NOT NULL,
    PRIMARY KEY (authorization_id, action_slug),
    CONSTRAINT fk_authorization_actions_authorization
        FOREIGN KEY (authorization_id) REFERENCES authorizations(id)
        ON DELETE CASCADE,
    CONSTRAINT fk_authorization_actions_action
        FOREIGN KEY (action_slug) REFERENCES installer_actions(slug)
        ON DELETE RESTRICT
) ENGINE=InnoDB;

ALTER TABLE authorization_packages
    ADD COLUMN IF NOT EXISTS package_slug VARCHAR(100) NULL,
    ADD COLUMN IF NOT EXISTS display_name VARCHAR(255) NULL,
    ADD COLUMN IF NOT EXISTS package_name VARCHAR(255) NULL,
    ADD COLUMN IF NOT EXISTS package_version VARCHAR(100) NULL,
    ADD COLUMN IF NOT EXISTS file_name VARCHAR(255) NULL,
    ADD COLUMN IF NOT EXISTS sha256 CHAR(64) NULL;

UPDATE authorization_packages ap
JOIN packages p ON p.id = ap.package_id
SET ap.package_slug = p.slug,
    ap.display_name = p.display_name,
    ap.package_name = p.package_name,
    ap.package_version = p.package_version,
    ap.file_name = p.file_name,
    ap.sha256 = p.sha256
WHERE ap.package_slug IS NULL;

ALTER TABLE authorization_packages
    MODIFY package_slug VARCHAR(100) NOT NULL,
    MODIFY display_name VARCHAR(255) NOT NULL,
    MODIFY package_name VARCHAR(255) NOT NULL,
    MODIFY package_version VARCHAR(100) NOT NULL,
    MODIFY file_name VARCHAR(255) NOT NULL,
    MODIFY sha256 CHAR(64) NOT NULL;

INSERT INTO installer_actions (slug, display_name, sort_order, enabled)
VALUES
    ('install-rmm', 'Install ConnectWise RMM agent', 10, TRUE),
    ('install-acronis', 'Install Acronis agent', 20, TRUE),
    ('install-screenconnect', 'Install ScreenConnect agent', 30, TRUE)
ON DUPLICATE KEY UPDATE
    display_name = VALUES(display_name),
    sort_order = VALUES(sort_order);

INSERT IGNORE INTO schema_migrations (version) VALUES (2);
