-- Migration: Add question_audit_log table
-- Date: 2025-11-27
-- Description: Add audit logging for question changes

CREATE TABLE IF NOT EXISTS question_audit_log (
    id SERIAL PRIMARY KEY,
    question_id INTEGER NOT NULL,
    checklist_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    action VARCHAR(50) NOT NULL,
    field_name VARCHAR(100),
    old_value TEXT,
    new_value TEXT,
    comment TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    
    -- Foreign keys
    CONSTRAINT fk_question_audit_question 
        FOREIGN KEY (question_id) 
        REFERENCES questions(id) 
        ON DELETE CASCADE,
    
    CONSTRAINT fk_question_audit_checklist 
        FOREIGN KEY (checklist_id) 
        REFERENCES checklists(id) 
        ON DELETE CASCADE,
    
    CONSTRAINT fk_question_audit_user 
        FOREIGN KEY (user_id) 
        REFERENCES users(id)
);

-- Create indexes for better query performance
CREATE INDEX idx_question_audit_question_id ON question_audit_log(question_id);
CREATE INDEX idx_question_audit_checklist_id ON question_audit_log(checklist_id);
CREATE INDEX idx_question_audit_created_at ON question_audit_log(created_at);
CREATE INDEX idx_question_audit_action ON question_audit_log(action);

-- Add comment to table
COMMENT ON TABLE question_audit_log IS 'Registro de auditoría para cambios en preguntas de checklists';
COMMENT ON COLUMN question_audit_log.action IS 'Tipo de acción: created, updated, deleted';
COMMENT ON COLUMN question_audit_log.field_name IS 'Nombre del campo modificado (solo para updates)';
COMMENT ON COLUMN question_audit_log.old_value IS 'Valor anterior del campo';
COMMENT ON COLUMN question_audit_log.new_value IS 'Valor nuevo del campo';
