-- migrations/20260629000000_fix_foreign_key_on_update.sql
-- 修复外键级联更新约束 (ON UPDATE CASCADE)

PRAGMA foreign_keys = OFF;

-- 1. 重建 notes 表
CREATE TABLE notes_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    bibcode TEXT NOT NULL,
    paragraph_index INTEGER NOT NULL,
    note_text TEXT NOT NULL DEFAULT '',
    highlight_color TEXT NOT NULL DEFAULT 'yellow',
    selected_text TEXT NOT NULL DEFAULT '',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (bibcode) REFERENCES papers(bibcode) ON DELETE CASCADE ON UPDATE CASCADE
);

INSERT INTO notes_new (id, bibcode, paragraph_index, note_text, highlight_color, selected_text, created_at)
SELECT id, bibcode, paragraph_index, note_text, highlight_color, selected_text, created_at FROM notes;

DROP TABLE notes;
ALTER TABLE notes_new RENAME TO notes;
CREATE INDEX IF NOT EXISTS idx_notes_bibcode ON notes(bibcode);

-- 2. 重建 paper_chunks_content 表
CREATE TABLE paper_chunks_content_new (
    rowid INTEGER PRIMARY KEY AUTOINCREMENT,
    bibcode TEXT,
    paragraph_index INTEGER,
    content TEXT,
    headings TEXT DEFAULT 'Document',
    section_index INTEGER DEFAULT 0,
    FOREIGN KEY(bibcode) REFERENCES papers(bibcode) ON DELETE CASCADE ON UPDATE CASCADE
);

INSERT INTO paper_chunks_content_new (rowid, bibcode, paragraph_index, content, headings, section_index)
SELECT rowid, bibcode, paragraph_index, content, headings, section_index FROM paper_chunks_content;

DROP TABLE paper_chunks_content;
ALTER TABLE paper_chunks_content_new RENAME TO paper_chunks_content;

-- 3. 重建 paper_targets 表
CREATE TABLE paper_targets_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    bibcode TEXT,
    target_name TEXT,
    ra TEXT,
    dec TEXT,
    parallax REAL,
    spectral_type TEXT,
    v_magnitude REAL,
    aliases TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    otype TEXT,
    oname TEXT,
    pm_ra REAL,
    pm_de REAL,
    radial_velocity REAL,
    parallax_err REAL,
    photometry TEXT,
    FOREIGN KEY(bibcode) REFERENCES papers(bibcode) ON DELETE CASCADE ON UPDATE CASCADE,
    UNIQUE(bibcode, target_name)
);

INSERT INTO paper_targets_new (id, bibcode, target_name, ra, dec, parallax, spectral_type, v_magnitude, aliases, created_at, otype, oname, pm_ra, pm_de, radial_velocity, parallax_err, photometry)
SELECT id, bibcode, target_name, ra, dec, parallax, spectral_type, v_magnitude, aliases, created_at, otype, oname, pm_ra, pm_de, radial_velocity, parallax_err, photometry FROM paper_targets;

DROP TABLE paper_targets;
ALTER TABLE paper_targets_new RENAME TO paper_targets;
CREATE INDEX IF NOT EXISTS idx_paper_targets_name ON paper_targets(target_name);

PRAGMA foreign_keys = ON;
