-- Add status and letter_incoming_id columns to letter_incoming_dispositions_department table

-- Add letter_incoming_id column
ALTER TABLE letter_incoming_dispositions_department
    ADD COLUMN IF NOT EXISTS letter_incoming_id UUID NOT NULL REFERENCES letters_incoming(id);

-- Add status column with default value
ALTER TABLE letter_incoming_dispositions_department
    ADD COLUMN IF NOT EXISTS status VARCHAR(50) NOT NULL DEFAULT 'pending';

-- Add read_at column
ALTER TABLE letter_incoming_dispositions_department
    ADD COLUMN IF NOT EXISTS read_at TIMESTAMP;

-- Add completed_at column
ALTER TABLE letter_incoming_dispositions_department
    ADD COLUMN IF NOT EXISTS completed_at TIMESTAMP;

-- Add updated_at column
ALTER TABLE letter_incoming_dispositions_department
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

-- Create index for faster queries
CREATE INDEX IF NOT EXISTS idx_letter_incoming_dispositions_department_status
    ON letter_incoming_dispositions_department(department_id, status);

CREATE INDEX IF NOT EXISTS idx_letter_incoming_dispositions_department_letter_id
    ON letter_incoming_dispositions_department(letter_incoming_id);

-- Update existing records to have status 'dispositioned' (assuming existing records are already dispositioned)
UPDATE letter_incoming_dispositions_department
SET status = 'dispositioned'
WHERE status = 'pending';

-- Add constraint to ensure valid status values
ALTER TABLE letter_incoming_dispositions_department
    ADD CONSTRAINT check_disposition_department_status
        CHECK (status IN ('pending', 'dispositioned', 'read', 'completed'));