-- Initialize MTG data database
CREATE DATABASE mtgdata;

-- Create extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pg_trgm";

-- Create mtgjson tables
CREATE TABLE IF NOT EXISTS mtg_sets (
    id SERIAL PRIMARY KEY,
    code VARCHAR(10) UNIQUE NOT NULL,
    name VARCHAR(255) NOT NULL,
    type VARCHAR(50),
    release_date DATE,
    base_set_size INTEGER,
    total_size INTEGER,
    is_foil_only BOOLEAN DEFAULT FALSE,
    is_non_foil_only BOOLEAN DEFAULT FALSE,
    digital BOOLEAN DEFAULT FALSE,
    icon_svg_url TEXT,
    parent_code VARCHAR(10),
    mtgo_code VARCHAR(10),
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS mtg_cards (
    id SERIAL PRIMARY KEY,
    set_id INTEGER REFERENCES mtg_sets(id),
    name VARCHAR(255) NOT NULL,
    mana_cost TEXT,
    type_line VARCHAR(255),
    oracle_text TEXT,
    power VARCHAR(10),
    toughness VARCHAR(10),
    rarity VARCHAR(50),
    layout VARCHAR(50),
    artist VARCHAR(255),
    flavor_text TEXT,
    numbers VARCHAR(50),
    identifiers JSONB,
    images JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_mtg_cards_set_id ON mtg_cards(set_id);
CREATE INDEX idx_mtg_cards_name ON mtg_cards(name);
CREATE INDEX idx_mtg_cards_type ON mtg_cards(type_line);

CREATE TABLE IF NOT EXISTS mtg_refresh_log (
    id SERIAL PRIMARY KEY,
    refresh_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status VARCHAR(50) NOT NULL,
    cards_updated INTEGER DEFAULT 0,
    sets_updated INTEGER DEFAULT 0,
    error_message TEXT,
    duration_seconds INTEGER
);

CREATE INDEX idx_mtg_refresh_log_date ON mtg_refresh_log(refresh_date);
