-- =============================================================
-- Migracja: Tabela order_payments
-- Cel: Przechowywanie platnosci zamowien (recznych i z importu)
-- Zrodlo schematu: database/drafts/20260302_orders_schema_v1.sql
-- Idempotentna: CREATE TABLE IF NOT EXISTS
-- =============================================================

CREATE TABLE IF NOT EXISTS order_payments (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    order_id INT UNSIGNED NOT NULL,
    source_payment_id VARCHAR(64) NULL,
    external_payment_id VARCHAR(64) NULL,
    payment_type_id VARCHAR(64) NOT NULL,
    payment_date DATETIME NULL,
    amount DECIMAL(12,2) NULL,
    currency CHAR(3) NULL,
    comment VARCHAR(255) NULL,
    payload_json JSON NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY order_payments_order_source_payment_unique (order_id, source_payment_id),
    KEY order_payments_order_idx (order_id),
    KEY order_payments_date_idx (payment_date),
    CONSTRAINT order_payments_order_fk
        FOREIGN KEY (order_id) REFERENCES orders(id)
        ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Kolumny payment w orders — idempotentne dodanie (mogly byc juz zaladowane z deploy scriptu)
SET @sql := (
    SELECT IF(COUNT(*) = 0,
        'ALTER TABLE `orders` ADD COLUMN `total_with_tax` DECIMAL(12,2) NULL AFTER `total_net`',
        'SELECT 1')
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'orders'
      AND column_name = 'total_with_tax'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql := (
    SELECT IF(COUNT(*) = 0,
        'ALTER TABLE `orders` ADD COLUMN `total_paid` DECIMAL(12,2) NULL AFTER `total_with_tax`',
        'SELECT 1')
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'orders'
      AND column_name = 'total_paid'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql := (
    SELECT IF(COUNT(*) = 0,
        'ALTER TABLE `orders` ADD COLUMN `external_payment_type_id` VARCHAR(128) NULL AFTER `payment_status`',
        'SELECT 1')
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'orders'
      AND column_name = 'external_payment_type_id'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
