BEGIN;

-- =======================
-- RENAME LETTER DISPOSITIONS TABLE
-- =======================
ALTER TABLE letter_dispositions RENAME TO letter_incoming_dispositions;

-- =======================
-- MODIFY LETTER INCOMING DISPOSITIONS TABLE STRUCTURE
-- =======================
-- Drop existing columns that are not needed
ALTER TABLE letter_incoming_dispositions DROP COLUMN IF EXISTS from_user_id;
ALTER TABLE letter_incoming_dispositions DROP COLUMN IF EXISTS to_user_id;
ALTER TABLE letter_incoming_dispositions DROP COLUMN IF EXISTS to_department_id;
ALTER TABLE letter_incoming_dispositions DROP COLUMN IF EXISTS status;
ALTER TABLE letter_incoming_dispositions DROP COLUMN IF EXISTS completed_at;

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

-- Add missing columns if they don't exist
ALTER TABLE letter_incoming_dispositions ADD COLUMN IF NOT EXISTS read_at TIMESTAMP WITHOUT TIME ZONE;
ALTER TABLE letter_incoming_dispositions ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP;

-- =======================
-- CREATE LETTER INCOMING DISPOSITIONS DEPARTMENT ASSOCIATION TABLE
-- =======================
CREATE TABLE IF NOT EXISTS letter_incoming_dispositions_department (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    letter_incoming_disposition_id UUID NOT NULL REFERENCES letter_incoming_dispositions(id) ON DELETE CASCADE,
    department_id UUID NOT NULL REFERENCES departments(id) ON DELETE CASCADE,
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (letter_incoming_disposition_id, department_id)
);

CREATE INDEX IF NOT EXISTS idx_letter_incoming_dispositions_department_disposition ON letter_incoming_dispositions_department(letter_incoming_disposition_id);
CREATE INDEX IF NOT EXISTS idx_letter_incoming_dispositions_department_dept ON letter_incoming_dispositions_department(department_id);

-- =======================
-- UPDATE TRIGGERS AND INDEXES
-- =======================
-- Drop old trigger
DROP TRIGGER IF EXISTS trg_letter_dispositions_updated_at ON letter_incoming_dispositions;

-- Create new trigger
CREATE TRIGGER trg_letter_incoming_dispositions_updated_at
    BEFORE UPDATE ON letter_incoming_dispositions
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();

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

COMMIT;
