-- Migration 007: Add media upload support
-- Per ADR-057: Social media attachment model
-- Per ADR-058: Image optimization strategy
-- Version: 1.2.0 Phase 3

-- Media storage table
-- Stores metadata for uploaded media files
CREATE TABLE IF NOT EXISTS media (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    filename TEXT NOT NULL,              -- Original filename from upload
    stored_filename TEXT NOT NULL,       -- UUID-based filename on disk
    path TEXT NOT NULL UNIQUE,           -- Full path: media/YYYY/MM/uuid.ext
    mime_type TEXT NOT NULL,             -- image/jpeg, image/png, etc.
    size INTEGER NOT NULL,               -- File size in bytes
    width INTEGER,                       -- Image width (pixels)
    height INTEGER,                      -- Image height (pixels)
    uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Note-media junction table
-- Per Q4: Upload after note creation, associate via note_id
-- Per Q7: Caption support for accessibility
CREATE TABLE IF NOT EXISTS note_media (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    note_id INTEGER NOT NULL,
    media_id INTEGER NOT NULL,
    display_order INTEGER NOT NULL DEFAULT 0,  -- Order for display (0-3)
    caption TEXT,                              -- Alt text / accessibility
    FOREIGN KEY (note_id) REFERENCES notes(id) ON DELETE CASCADE,
    FOREIGN KEY (media_id) REFERENCES media(id) ON DELETE CASCADE,
    UNIQUE(note_id, media_id)
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_media_uploaded ON media(uploaded_at);
CREATE INDEX IF NOT EXISTS idx_note_media_note ON note_media(note_id);
CREATE INDEX IF NOT EXISTS idx_note_media_order ON note_media(note_id, display_order);
