-- 013: Fix record_workspace_audit() for tables without 'id' column.
-- workspace_billing, workspace_custom_branding, workspace_settings
-- use workspace_id as their PRIMARY KEY and have no separate id column.
-- The original function unconditionally referenced NEW.id, which crashed
-- with "record 'new' has no field 'id'" (42703).

CREATE OR REPLACE FUNCTION record_workspace_audit()
RETURNS TRIGGER AS $$
DECLARE
    ws_id UUID;
    actor UUID := app_current_user_id();
    action_text TEXT;
    target_id_val UUID;
BEGIN
    ws_id := COALESCE(NEW.workspace_id, OLD.workspace_id);

    IF ws_id IS NULL THEN
        RETURN COALESCE(NEW, OLD);
    END IF;

    action_text := CASE TG_OP
        WHEN 'INSERT' THEN 'created'
        WHEN 'UPDATE' THEN 'updated'
        WHEN 'DELETE' THEN 'deleted'
    END;

    -- Attempt to read NEW.id / OLD.id. For tables whose PK is workspace_id
    -- there is no id column; catch the error and use ws_id instead.
    BEGIN
        target_id_val := COALESCE(NEW.id, OLD.id);
    EXCEPTION
        WHEN undefined_column THEN
            target_id_val := ws_id;
    END;

    INSERT INTO workspace_audit_log (workspace_id, actor_id, action, target_type, target_id, created_at)
    VALUES (ws_id, actor, action_text, TG_TABLE_NAME, target_id_val, NOW());

    RETURN COALESCE(NEW, OLD);
END;
$$ LANGUAGE plpgsql;
