CREATE INDEX IF NOT EXISTS idx_mail_accounts_user_created
    ON mail_accounts(user_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_messages_account_date
    ON messages(account_id, date DESC);

CREATE INDEX IF NOT EXISTS idx_messages_folder_date
    ON messages(folder_id, date DESC);

CREATE INDEX IF NOT EXISTS idx_mail_rules_user_active_priority
    ON mail_rules(user_id, is_active, priority);

CREATE INDEX IF NOT EXISTS idx_webhook_templates_user_active
    ON webhook_templates(user_id, is_active);

CREATE INDEX IF NOT EXISTS idx_outbox_status_created
    ON outbox(status, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_outbox_account_status
    ON outbox(account_id, status);

CREATE UNIQUE INDEX IF NOT EXISTS uq_mail_accounts_id_user
    ON mail_accounts(id, user_id);

CREATE UNIQUE INDEX IF NOT EXISTS uq_mail_folders_id_account
    ON mail_folders(id, account_id);

ALTER TABLE messages
    ADD CONSTRAINT messages_folder_account_fk
    FOREIGN KEY (folder_id, account_id)
    REFERENCES mail_folders(id, account_id)
    ON DELETE CASCADE
    NOT VALID;

ALTER TABLE outbox
    ADD CONSTRAINT outbox_account_user_fk
    FOREIGN KEY (account_id, user_id)
    REFERENCES mail_accounts(id, user_id)
    ON DELETE CASCADE
    NOT VALID;

ALTER TABLE mail_rules
    ADD CONSTRAINT mail_rules_account_user_fk
    FOREIGN KEY (account_id, user_id)
    REFERENCES mail_accounts(id, user_id)
    ON DELETE CASCADE
    NOT VALID;

ALTER TABLE attachments
    ADD CONSTRAINT attachments_size_nonnegative_chk
    CHECK (size >= 0) NOT VALID;

ALTER TABLE messages
    ADD CONSTRAINT messages_raw_size_nonnegative_chk
    CHECK (raw_size >= 0) NOT VALID;

ALTER TABLE webhook_logs
    ADD CONSTRAINT webhook_logs_duration_nonnegative_chk
    CHECK (duration_ms >= 0) NOT VALID;

ALTER TABLE outbox
    ADD CONSTRAINT outbox_retry_count_nonnegative_chk
    CHECK (retry_count >= 0) NOT VALID;
