-- 001: 초기 스키마 생성
-- events, news, osint, users, login_history

SET search_path TO kcg;

-- 이벤트 테이블 (GDELT 등 이벤트 데이터)
CREATE TABLE IF NOT EXISTS events (
    id              BIGSERIAL PRIMARY KEY,
    event_id        VARCHAR(64) UNIQUE,
    title           TEXT NOT NULL,
    description     TEXT,
    source          VARCHAR(128),
    source_url      TEXT,
    category        VARCHAR(64),
    latitude        DOUBLE PRECISION,
    longitude       DOUBLE PRECISION,
    timestamp       TIMESTAMP NOT NULL,
    raw_data        JSONB,
    created_at      TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events (timestamp);

-- 뉴스 테이블
CREATE TABLE IF NOT EXISTS news (
    id              BIGSERIAL PRIMARY KEY,
    title           TEXT NOT NULL,
    summary         TEXT,
    source          VARCHAR(128),
    source_url      TEXT UNIQUE,
    category        VARCHAR(64),
    language        VARCHAR(8),
    timestamp       TIMESTAMP NOT NULL,
    raw_data        JSONB,
    created_at      TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_news_timestamp ON news (timestamp);

-- OSINT 테이블
CREATE TABLE IF NOT EXISTS osint (
    id              BIGSERIAL PRIMARY KEY,
    title           TEXT NOT NULL,
    content         TEXT,
    source          VARCHAR(128),
    source_url      TEXT UNIQUE,
    category        VARCHAR(64),
    credibility     SMALLINT,
    latitude        DOUBLE PRECISION,
    longitude       DOUBLE PRECISION,
    timestamp       TIMESTAMP NOT NULL,
    raw_data        JSONB,
    created_at      TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_osint_timestamp ON osint (timestamp);
CREATE INDEX IF NOT EXISTS idx_osint_category ON osint (category);

-- 사용자 테이블
CREATE TABLE IF NOT EXISTS users (
    id              BIGSERIAL PRIMARY KEY,
    email           VARCHAR(255) NOT NULL UNIQUE,
    name            VARCHAR(128) NOT NULL,
    picture         TEXT,
    last_login_at   TIMESTAMP,
    created_at      TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_users_email ON users (email);

-- 로그인 이력 테이블
CREATE TABLE IF NOT EXISTS login_history (
    id              BIGSERIAL PRIMARY KEY,
    user_id         BIGINT NOT NULL REFERENCES users(id),
    login_at        TIMESTAMP NOT NULL DEFAULT NOW(),
    ip_address      VARCHAR(45),
    user_agent      TEXT,
    success         BOOLEAN NOT NULL DEFAULT TRUE,
    failure_reason  VARCHAR(100)
);

CREATE INDEX IF NOT EXISTS idx_login_history_user_id ON login_history (user_id);
CREATE INDEX IF NOT EXISTS idx_login_history_login_at ON login_history (login_at);
