CREATE TABLE IF NOT EXISTS posts (
    id TEXT PRIMARY KEY,
    anonymous_user_id TEXT NOT NULL,
    content_type TEXT NOT NULL CHECK(content_type IN ('text', 'voice', 'photo')),
    content_data TEXT NOT NULL,
    emotion_tag TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    expires_at DATETIME NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_posts_anonymous_user_id ON posts (anonymous_user_id);
CREATE INDEX IF NOT EXISTS idx_posts_expires_at ON posts (expires_at);

CREATE TABLE IF NOT EXISTS holds (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    post_id TEXT NOT NULL,
    anonymous_user_id TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
    UNIQUE(post_id, anonymous_user_id)
);

CREATE TABLE IF NOT EXISTS reports (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    post_id TEXT NOT NULL,
    reporter_anonymous_user_id TEXT NOT NULL,
    reason TEXT,
    status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'reviewed')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_reports_status ON reports (status);

CREATE TABLE IF NOT EXISTS post_summaries (
    id TEXT PRIMARY KEY,
    anonymous_user_id TEXT NOT NULL,
    emotion_tag TEXT NOT NULL,
    hold_count INTEGER NOT NULL,
    dissolved_at DATETIME NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_post_summaries_anonymous_user_id ON post_summaries (anonymous_user_id);

CREATE TABLE IF NOT EXISTS users (
   email TEXT PRIMARY KEY,
   username TEXT UNIQUE,
   fullName TEXT NOT NULL,
   mauth_token TEXT,
   phone TEXT,
   citizen_id TEXT,
   role TEXT DEFAULT 'visitor' CHECK(role IN ('visitor', 'moderator', 'admin')),
   avatar_url TEXT,
   bio TEXT,
   id_document_url TEXT,
   id_verification_status TEXT DEFAULT 'pending' CHECK(id_verification_status IN ('pending', 'verified', 'rejected')),
   created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS settings (
   key TEXT PRIMARY KEY,
   value TEXT NOT NULL
);

INSERT INTO settings (key, value) VALUES ('site_name', 'Cloudflare D1 App');
INSERT INTO settings (key, value) VALUES ('default_post_ttl_hours', '24');
INSERT INTO settings (key, value) VALUES ('maintenance_mode', 'false');
INSERT INTO settings (key, value) VALUES ('max_report_count_before_auto_hide', '5');