-- Initialize MTG data database
-- Uses $POSTGRES_USER from environment

-- Create mtgdata database if it doesn't exist (owned by the POSTGRES_USER)
SELECT 'CREATE DATABASE mtgdata OWNER ' || current_user
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mtgdata')\gexec

-- Connect to mtgdata and set up schema permissions
\c mtgdata

-- Grant all privileges to the app user
GRANT ALL PRIVILEGES ON DATABASE mtgdata TO current_user;
GRANT ALL ON SCHEMA public TO current_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO current_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO current_user;

-- 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);
