BEGIN;

-- =======================
-- DROP NEW ASSOCIATION TABLE
-- =======================
DROP TABLE IF EXISTS letter_incoming_dispositions_department;

-- =======================
-- RESTORE LETTER DISPOSITIONS TABLE STRUCTURE
-- =======================
-- Add back the columns that were removed
ALTER TABLE letter_incoming_dispositions ADD COLUMN IF NOT EXISTS from_user_id UUID REFERENCES users(id) ON DELETE SET NULL;
ALTER TABLE letter_incoming_dispositions ADD COLUMN IF NOT EXISTS to_user_id UUID REFERENCES users(id) ON DELETE SET NULL;
ALTER TABLE letter_incoming_dispositions ADD COLUMN IF NOT EXISTS to_department_id UUID REFERENCES departments(id) ON DELETE SET NULL;
ALTER TABLE letter_incoming_dispositions ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','read','rejected','completed'));
ALTER TABLE letter_incoming_dispositions ADD COLUMN IF NOT EXISTS completed_at TIMESTAMP WITHOUT TIME ZONE;

-- Rename department_id back to from_department_id
ALTER TABLE letter_incoming_dispositions RENAME COLUMN department_id TO from_department_id;

-- =======================
-- RESTORE TRIGGERS AND INDEXES
-- =======================
-- Drop new trigger
DROP TRIGGER IF EXISTS trg_letter_incoming_dispositions_updated_at ON letter_incoming_dispositions;

-- Restore old trigger
CREATE TRIGGER trg_letter_dispositions_updated_at
    BEFORE UPDATE ON letter_incoming_dispositions
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();

-- Restore index names
DROP INDEX IF EXISTS idx_letter_incoming_dispositions_letter;
CREATE INDEX IF NOT EXISTS idx_letter_dispositions_letter ON letter_incoming_dispositions(letter_id);

-- =======================
-- RENAME TABLE BACK
-- =======================
ALTER TABLE letter_incoming_dispositions RENAME TO letter_dispositions;

COMMIT;
