-- Migration 005: Advanced Pricing (Defensive Update)

-- 1. Ensure services table exists (minimal version)
CREATE TABLE IF NOT EXISTS `services` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name_en` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 2. Add columns to services (ignoring if they exist is handled by the fact that migrations are atomic per statement here)
-- Note: if a column exists, the script will show an error but run_migrations.py will continue to next statement.
ALTER TABLE `services` ADD COLUMN `name_ru` varchar(255) DEFAULT NULL;
ALTER TABLE `services` ADD COLUMN `name_ua` varchar(255) DEFAULT NULL;
ALTER TABLE `services` ADD COLUMN `desc_en` text DEFAULT NULL;
ALTER TABLE `services` ADD COLUMN `tech_type` varchar(50) DEFAULT 'fdm';
ALTER TABLE `services` ADD COLUMN `price_per_hour` decimal(10,2) DEFAULT 0.00;
ALTER TABLE `services` ADD COLUMN `is_active` tinyint(1) DEFAULT 1;
ALTER TABLE `services` ADD COLUMN `created_at` timestamp DEFAULT CURRENT_TIMESTAMP;

-- 3. Add columns to materials
ALTER TABLE `materials` ADD COLUMN `price_per_hour` decimal(10,2) DEFAULT NULL;
ALTER TABLE `materials` ADD COLUMN `speed_coeff` decimal(10,2) DEFAULT 1.00;
ALTER TABLE `materials` ADD COLUMN `service_id` int(11) DEFAULT NULL;

-- 4. Initial seed for services
INSERT INTO `services` (`name_en`, `name_ru`, `name_ua`, `tech_type`, `price_per_hour`)
SELECT 'FDM Printing', 'FDM Печать', 'FDM Друк', 'fdm', 2.00
FROM (SELECT 1) AS tmp
WHERE NOT EXISTS (SELECT 1 FROM `services` WHERE `tech_type` = 'fdm') LIMIT 1;

INSERT INTO `services` (`name_en`, `name_ru`, `name_ua`, `tech_type`, `price_per_hour`)
SELECT 'SLA Printing', 'SLA Печать', 'SLA Друк', 'sla', 5.00
FROM (SELECT 1) AS tmp
WHERE NOT EXISTS (SELECT 1 FROM `services` WHERE `tech_type` = 'sla') LIMIT 1;
