"""Neutralization SQL for Odoo databases.

Extracted from OdooBackupRestore.neutralize_database() for reuse
in Docker export (written as standalone neutralize.sql in the archive).
"""

# Core neutralization SQL - mirrors backup_restore.py neutralize_database()
CORE_NEUTRALIZE_SQL = """
-- =============================================================
-- Odoo Database Neutralization for Dev/Test
-- Generated by odoo-backup-manager Docker Export
-- =============================================================

-- Disable all outgoing mail servers and clear credentials
UPDATE ir_mail_server
SET active = false,
    smtp_user = NULL,
    smtp_pass = NULL,
    smtp_host = 'disabled.example.com',
    smtp_port = 25;

-- Disable the "Use Custom Email Servers" system parameter
UPDATE ir_config_parameter
SET value = 'False'
WHERE key = 'mail.use_email_servers';

INSERT INTO ir_config_parameter (key, value)
SELECT 'mail.use_email_servers', 'False'
WHERE NOT EXISTS (
    SELECT 1 FROM ir_config_parameter
    WHERE key = 'mail.use_email_servers'
);

-- Disable all scheduled actions (crons)
UPDATE ir_cron SET active = false;

-- Clear all email queues
DELETE FROM mail_mail WHERE state IN ('outgoing', 'exception', 'cancel');

-- Clear email from fetchmail servers if module is installed
DO $$
BEGIN
    IF EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'fetchmail_server') THEN
        UPDATE fetchmail_server SET active = false WHERE active = true;
        UPDATE fetchmail_server
        SET "user" = NULL,
            password = NULL,
            server = 'disabled.example.com'
        WHERE active = false;
    END IF;
END $$;

-- Disable all payment acquirers if module is installed
DO $$
BEGIN
    IF EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'payment_acquirer') THEN
        UPDATE payment_acquirer SET state = 'disabled' WHERE state != 'disabled';
    END IF;
END $$;

-- Disable website robots.txt indexing if website module is installed
DO $$
BEGIN
    IF EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'website') THEN
        UPDATE website SET robots_txt = E'User-agent: *\\nDisallow: /'
        WHERE robots_txt IS NULL OR robots_txt != E'User-agent: *\\nDisallow: /';
    END IF;
END $$;

-- Add warning message to company name
UPDATE res_company
SET name = CONCAT('[TEST] ', name)
WHERE name NOT LIKE '[TEST]%%';

-- Neutralize Enterprise license code
UPDATE ir_config_parameter
SET value = CONCAT('NEUTRALIZED-', value)
WHERE key = 'database.enterprise_code'
AND value NOT LIKE 'NEUTRALIZED-%%';

-- Clear license expiration date
DELETE FROM ir_config_parameter
WHERE key IN ('database.expiration_date', 'database.expiration_reason');

-- Log neutralization
INSERT INTO ir_logging (create_date, create_uid, name, type, dbname, level, message, path, line, func)
VALUES (
    NOW(),
    1,
    'odoo.neutralization',
    'server',
    current_database(),
    'WARNING',
    'Database has been neutralized for testing purposes (Docker export)',
    'odoo_backup_tool',
    0,
    'neutralize'
);
"""


def get_neutralize_sql(custom_sql=""):
    """Build complete neutralization SQL.

    Args:
        custom_sql: Optional additional SQL appended after core rules

    Returns:
        Complete SQL string ready to write to file
    """
    sql = CORE_NEUTRALIZE_SQL.strip()
    if custom_sql:
        sql += "\n\n-- Custom neutralization rules\n" + custom_sql.strip()
    return sql + "\n"
