-- ============================================================
-- Toasty — Migration 002 : Billing, Push Queue, Webhooks
-- MySQL 8.0+
-- Idempotent : utilise IF NOT EXISTS
-- ============================================================

-- ============================================================
-- TABLE: billing_plans
-- Plans tarifaires Toasty (référentiel statique)
-- ============================================================
CREATE TABLE IF NOT EXISTS billing_plans (
    id            INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name          VARCHAR(50)     NOT NULL UNIQUE  COMMENT 'free, starter, growth, pro',
    display_name  VARCHAR(100)    NOT NULL,
    price         DECIMAL(8, 2)   NOT NULL DEFAULT 0.00,
    notifications_per_month INT UNSIGNED NOT NULL DEFAULT 0,
    features      JSON,
    is_active     BOOLEAN         NOT NULL DEFAULT 1,
    created_at    TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    KEY idx_name (name),
    KEY idx_is_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Données initiales des plans (safe à rejouer)
INSERT INTO billing_plans (name, display_name, price, notifications_per_month, features)
VALUES
    ('free',    'Free',    0.00,  5000,   '["basic_push","1_campaign_per_month","email_support"]'),
    ('starter', 'Starter', 14.00, 25000,  '["unlimited_campaigns","priority_support","api_access"]'),
    ('growth',  'Growth',  29.00, 75000,  '["advanced_targeting","team_members","analytics"]'),
    ('pro',     'Pro',     59.00, 250000, '["custom_integrations","dedicated_support","webhooks"]')
ON DUPLICATE KEY UPDATE
    price                   = VALUES(price),
    notifications_per_month = VALUES(notifications_per_month),
    features                = VALUES(features);

-- ============================================================
-- TABLE: billing_subscriptions
-- Abonnements Shopify actifs (via AppSubscription API)
-- ============================================================
CREATE TABLE IF NOT EXISTS billing_subscriptions (
    id                       INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    shop_id                  INT UNSIGNED    NOT NULL,
    billing_plan_id          INT UNSIGNED    NOT NULL,
    shopify_subscription_id  VARCHAR(255),
    shopify_charge_id        VARCHAR(255),
    status                   VARCHAR(50)     NOT NULL DEFAULT 'pending'
                             COMMENT 'pending, active, cancelled, failed',
    return_url               VARCHAR(500),
    next_billing_date        DATE,
    activated_at             TIMESTAMP NULL,
    cancelled_at             TIMESTAMP NULL,
    created_at               TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    updated_at               TIMESTAMP       DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_shop (shop_id),
    FOREIGN KEY (shop_id)         REFERENCES shops(id)         ON DELETE CASCADE,
    FOREIGN KEY (billing_plan_id) REFERENCES billing_plans(id) ON DELETE RESTRICT,
    KEY idx_status (status),
    KEY idx_next_billing_date (next_billing_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- TABLE: billing_history
-- Historique des charges (abonnements + crédits extra)
-- ============================================================
CREATE TABLE IF NOT EXISTS billing_history (
    id               INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    shop_id          INT UNSIGNED    NOT NULL,
    subscription_id  INT UNSIGNED,
    amount           DECIMAL(8, 2)   NOT NULL,
    currency         VARCHAR(3)      NOT NULL DEFAULT 'USD',
    billing_type     VARCHAR(50)     NOT NULL COMMENT 'subscription, extra_credit',
    description      VARCHAR(255),
    status           VARCHAR(50)     NOT NULL DEFAULT 'pending'
                     COMMENT 'pending, paid, failed',
    invoice_url      VARCHAR(500),
    billed_at        TIMESTAMP NULL,
    created_at       TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (shop_id)         REFERENCES shops(id)                  ON DELETE CASCADE,
    FOREIGN KEY (subscription_id) REFERENCES billing_subscriptions(id)  ON DELETE SET NULL,
    KEY idx_shop_id (shop_id),
    KEY idx_status (status),
    KEY idx_billed_at (billed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- TABLE: extra_credits
-- Crédits supplémentaires ($5 / 5 000 notifs, sans expiration)
-- ============================================================
CREATE TABLE IF NOT EXISTS extra_credits (
    id           INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    shop_id      INT UNSIGNED    NOT NULL,
    quantity     INT UNSIGNED    NOT NULL COMMENT 'Notifications achetées',
    remaining    INT UNSIGNED    NOT NULL COMMENT 'Notifications restantes',
    purchased_at TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    expires_at   TIMESTAMP NULL  DEFAULT NULL COMMENT 'NULL = jamais',
    FOREIGN KEY (shop_id) REFERENCES shops(id) ON DELETE CASCADE,
    KEY idx_shop_id (shop_id),
    KEY idx_remaining (remaining)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- TABLE: push_queue
-- Queue asynchrone pour envoi Redis/worker
-- ============================================================
CREATE TABLE IF NOT EXISTS push_queue (
    id            INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    shop_id       INT UNSIGNED    NOT NULL,
    campaign_id   INT UNSIGNED,
    subscriber_id INT UNSIGNED    NOT NULL,
    push_type     VARCHAR(20)     NOT NULL DEFAULT 'web' COMMENT 'web, mobile',
    payload       JSON            NOT NULL,
    status        VARCHAR(20)     NOT NULL DEFAULT 'pending'
                  COMMENT 'pending, processing, sent, failed',
    attempts      TINYINT UNSIGNED NOT NULL DEFAULT 0,
    max_attempts  TINYINT UNSIGNED NOT NULL DEFAULT 3,
    error_message TEXT,
    process_after TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    sent_at       TIMESTAMP NULL,
    failed_at     TIMESTAMP NULL,
    created_at    TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (shop_id)       REFERENCES shops(id)       ON DELETE CASCADE,
    FOREIGN KEY (campaign_id)   REFERENCES campaigns(id)   ON DELETE SET NULL,
    FOREIGN KEY (subscriber_id) REFERENCES subscribers(id) ON DELETE CASCADE,
    KEY idx_status_process (status, process_after) COMMENT 'Index principal du worker',
    KEY idx_campaign_id (campaign_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- TABLE: webhooks
-- Webhooks Shopify enregistrés par shop
-- ============================================================
CREATE TABLE IF NOT EXISTS webhooks (
    id                 INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    shop_id            INT UNSIGNED    NOT NULL,
    topic              VARCHAR(100)    NOT NULL
                       COMMENT 'orders/create, app/uninstalled, etc.',
    shopify_webhook_id VARCHAR(255),
    address            VARCHAR(500)    NOT NULL,
    is_active          BOOLEAN         NOT NULL DEFAULT 1,
    created_at         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    updated_at         TIMESTAMP       DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (shop_id) REFERENCES shops(id) ON DELETE CASCADE,
    UNIQUE KEY unique_shop_topic (shop_id, topic),
    KEY idx_shop_id (shop_id),
    KEY idx_topic (topic)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================================
-- TABLE: audit_logs
-- Traçabilité des actions admin (compliance)
-- ============================================================
CREATE TABLE IF NOT EXISTS audit_logs (
    id            INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    shop_id       INT UNSIGNED,
    admin_id      INT UNSIGNED,
    action        VARCHAR(100)    NOT NULL,
    resource_type VARCHAR(100),
    resource_id   INT UNSIGNED,
    changes       JSON,
    ip_address    VARCHAR(45),
    user_agent    VARCHAR(500),
    created_at    TIMESTAMP       DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (shop_id)  REFERENCES shops(id)  ON DELETE SET NULL,
    FOREIGN KEY (admin_id) REFERENCES admins(id) ON DELETE SET NULL,
    KEY idx_shop_id (shop_id),
    KEY idx_admin_id (admin_id),
    KEY idx_action (action),
    KEY idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
