# Generated by hand on 2025-12-29
# Creates APIToken and OutboundWebhook tables using raw SQL

from django.db import migrations


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0012_alter_user_first_name_max_length'),
    ]

    operations = [
        migrations.RunSQL(
            # Forward SQL
            sql="""
                -- Create api_apitoken table
                CREATE TABLE IF NOT EXISTS api_apitoken (
                    id TEXT PRIMARY KEY NOT NULL,
                    created_at DATETIME NOT NULL,
                    modified_at DATETIME NOT NULL,
                    num_uses_succeeded INTEGER NOT NULL DEFAULT 0,
                    num_uses_failed INTEGER NOT NULL DEFAULT 0,

                    token VARCHAR(32) NOT NULL UNIQUE,
                    label VARCHAR(64) NOT NULL DEFAULT '',
                    notes TEXT NOT NULL DEFAULT '',
                    expires DATETIME,

                    created_by_id INTEGER NOT NULL,

                    FOREIGN KEY (created_by_id) REFERENCES auth_user(id) ON DELETE CASCADE
                );
                CREATE INDEX IF NOT EXISTS api_apitoken_created_by_id_idx ON api_apitoken(created_by_id);
                CREATE INDEX IF NOT EXISTS api_apitoken_token_idx ON api_apitoken(token);

                -- Create api_outboundwebhook table
                CREATE TABLE IF NOT EXISTS api_outboundwebhook (
                    id TEXT PRIMARY KEY NOT NULL,
                    created_at DATETIME NOT NULL,
                    modified_at DATETIME NOT NULL,
                    num_uses_succeeded INTEGER NOT NULL DEFAULT 0,
                    num_uses_failed INTEGER NOT NULL DEFAULT 0,

                    name VARCHAR(255) NOT NULL UNIQUE,
                    signal VARCHAR(255) NOT NULL,
                    ref VARCHAR(1024) NOT NULL,
                    endpoint VARCHAR(2048) NOT NULL,
                    headers TEXT NOT NULL DEFAULT '{}',
                    enabled BOOLEAN NOT NULL DEFAULT 1,
                    keep_last_response BOOLEAN NOT NULL DEFAULT 0,
                    last_response TEXT,
                    last_success DATETIME,
                    last_error DATETIME,

                    created_by_id INTEGER NOT NULL,

                    FOREIGN KEY (created_by_id) REFERENCES auth_user(id) ON DELETE CASCADE
                );
                CREATE INDEX IF NOT EXISTS api_outboundwebhook_created_by_id_idx ON api_outboundwebhook(created_by_id);
                CREATE INDEX IF NOT EXISTS api_outboundwebhook_name_idx ON api_outboundwebhook(name);
                CREATE INDEX IF NOT EXISTS api_outboundwebhook_ref_idx ON api_outboundwebhook(ref);
            """,
            # Reverse SQL
            reverse_sql="""
                DROP TABLE IF EXISTS api_outboundwebhook;
                DROP TABLE IF EXISTS api_apitoken;
            """
        ),
    ]
