CREATE TABLE IF NOT EXISTS `cards` (
    `scryfall_id` TEXT PRIMARY KEY,
    `name` TEXT NOT NULL,
    `set_code` TEXT NOT NULL,
    `collector_number` TEXT NOT NULL,
    `release_date` TEXT NOT NULL,
    `rarity` TEXT NOT NULL,
    `color_identity` TEXT NOT NULL,
    `cmc` TEXT NOT NULL, -- Decimal value
    `type_line` TEXT NOT NULL,
    `foil` INTEGER NOT NULL DEFAULT 0,
    `nonfoil` INTEGER NOT NULL DEFAULT 1,
    `variation` INTEGER NOT NULL DEFAULT 0,
    `edhrec_rank` INTEGER,
    `oracle_text` TEXT
);

CREATE INDEX `cards_name` ON `cards`(`name` COLLATE nocase);
CREATE INDEX `cards_rarity` ON `cards`(`rarity`);
CREATE INDEX `cards_color_identity` ON `cards`(`color_identity`);

CREATE TABLE IF NOT EXISTS `copies` (
    `id` INTEGER PRIMARY KEY AUTOINCREMENT,
    `collection` TEXT NOT NULL DEFAULT 'Default',
    `scryfall_id` TEXT,
    `isFoil` INTEGER NOT NULL DEFAULT 0,
    `language` TEXT,
    `condition` TEXT,
    FOREIGN KEY (`scryfall_id`) REFERENCES `cards`(`scryfall_id`)
);

CREATE TABLE IF NOT EXISTS `card_prices` (
    `scryfall_id` TEXT,
    `date` TEXT,
    `usd` TEXT, -- Decimal value
    `usd_foil` TEXT, -- Decimal value
    `eur` TEXT, -- Decimal value
    `eur_foil` TEXT, -- Decimal value
    `tix` TEXT, -- Decimal value
    PRIMARY KEY (`scryfall_id`, `date`),
    FOREIGN KEY (`scryfall_id`) REFERENCES `cards`(`scryfall_id`)
);

CREATE TABLE IF NOT EXISTS `sets` (
    `set_code` TEXT PRIMARY KEY,
    `name` TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS `rarities` (
    `rarity` TEXT PRIMARY KEY,
    `rarity_ord` INTEGER NOT NULL
);

DELETE FROM `rarities`;
INSERT INTO `rarities` (`rarity`, `rarity_ord`) VALUES
('common', 1),
('uncommon', 2),
('rare', 3),
('special', 4),
('mythic', 5),
('bonus', 6);

CREATE TABLE IF NOT EXISTS `legalities` (
    `scryfall_id` TEXT NOT NULL,
    `format` TEXT NOT NULL,
    `legality` TEXT NOT NULL,
    PRIMARY KEY (`scryfall_id`, `format`),
    FOREIGN KEY (`scryfall_id`) REFERENCES `cards`(`scryfall_id`)
);

CREATE TABLE IF NOT EXISTS `games` (
    `scryfall_id` TEXT NOT NULL,
    `game` TEXT NOT NULL, -- 'paper', 'arena', or 'mtgo'
    PRIMARY KEY (`scryfall_id`, `game`),
    FOREIGN KEY (`scryfall_id`) REFERENCES `cards`(`scryfall_id`)
);

CREATE TABLE IF NOT EXISTS `vars` (
    `key` TEXT PRIMARY KEY,
    `value` TEXT
);
