-- Reverse 2026-05-10-000000_entity_facts_persona_fk: drop the
-- composite FK and the user_id column via the same rebuild pattern.

DROP INDEX IF EXISTS idx_entity_facts_user_persona;
DROP INDEX IF EXISTS idx_entity_facts_persona;
DROP INDEX IF EXISTS idx_entity_facts_source_photo;
DROP INDEX IF EXISTS idx_entity_facts_status;
DROP INDEX IF EXISTS idx_entity_facts_predicate;
DROP INDEX IF EXISTS idx_entity_facts_subject;

ALTER TABLE entity_facts RENAME TO entity_facts_old;

CREATE TABLE entity_facts (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    subject_entity_id INTEGER NOT NULL,
    predicate TEXT NOT NULL,
    object_entity_id INTEGER,
    object_value TEXT,
    source_photo TEXT,
    source_insight_id INTEGER,
    confidence REAL NOT NULL DEFAULT 0.6,
    status TEXT NOT NULL DEFAULT 'active',
    created_at BIGINT NOT NULL,
    persona_id TEXT NOT NULL DEFAULT 'default',
    CONSTRAINT fk_ef_subject FOREIGN KEY (subject_entity_id) REFERENCES entities(id) ON DELETE CASCADE,
    CONSTRAINT fk_ef_object  FOREIGN KEY (object_entity_id)  REFERENCES entities(id) ON DELETE SET NULL,
    CONSTRAINT fk_ef_insight FOREIGN KEY (source_insight_id) REFERENCES photo_insights(id) ON DELETE SET NULL,
    CHECK (object_entity_id IS NOT NULL OR object_value IS NOT NULL)
);

INSERT INTO entity_facts
    (id, subject_entity_id, predicate, object_entity_id, object_value,
     source_photo, source_insight_id, confidence, status, created_at,
     persona_id)
SELECT
    id, subject_entity_id, predicate, object_entity_id, object_value,
    source_photo, source_insight_id, confidence, status, created_at,
    persona_id
FROM entity_facts_old;

DROP TABLE entity_facts_old;

CREATE INDEX idx_entity_facts_subject ON entity_facts(subject_entity_id);
CREATE INDEX idx_entity_facts_predicate ON entity_facts(predicate);
CREATE INDEX idx_entity_facts_status ON entity_facts(status);
CREATE INDEX idx_entity_facts_source_photo ON entity_facts(source_photo);
CREATE INDEX idx_entity_facts_persona ON entity_facts(persona_id);
