package database

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/mattn/go-sqlite3"
)

func InitDB(db *sql.DB) {
	schema := `
    CREATE TABLE IF NOT EXISTS currencies (
        id   INTEGER PRIMARY KEY AUTOINCREMENT,
        code TEXT    NOT NULL UNIQUE,
        name TEXT    NOT NULL
    );

    CREATE TABLE IF NOT EXISTS trades (
        id            INTEGER PRIMARY KEY AUTOINCREMENT,
        symbol        TEXT    NOT NULL,
        currency_code TEXT    NOT NULL,
        shares        INTEGER NOT NULL,
        product       INTEGER NOT NULL CHECK(product IN (0, 1, 2, 3, 4)), -- added 4 for BondTrade
        type          INTEGER NOT NULL CHECK(type IN (0, 1)),             -- Buy=0, Sell=1 only; Dividend has its own table
        price         REAL    NOT NULL,
        traded_at     DATETIME NOT NULL
    );

    CREATE TABLE IF NOT EXISTS dividends (
        id            INTEGER PRIMARY KEY AUTOINCREMENT,
        symbol        TEXT    NOT NULL,
        currency_code TEXT    NOT NULL,
        product       INTEGER NOT NULL CHECK(product IN (0, 1, 2, 3, 4)),
        value         REAL    NOT NULL,
        tax_amount    REAL    NOT NULL DEFAULT 0,
        tax_rate      REAL    NOT NULL DEFAULT 0,
        net_value     REAL    NOT NULL,
        payment_date  DATETIME NOT NULL
    );

    CREATE TABLE IF NOT EXISTS position (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        company_id  INTEGER NOT NULL UNIQUE,
        symbol TEXT NOT NULL,
        currency_id INTEGER NOT NULL,
        currency_code TEXT NOT NULL,
        shares      INTEGER NOT NULL,
        weight      REAL NOT NULL,
        cost_basis  REAL NOT NULL,
        FOREIGN KEY (currency_id) REFERENCES currencies(id),
        FOREIGN KEY (company_id) REFERENCES companies(id)
    );

    CREATE TABLE IF NOT EXISTS companies (
        id                 INTEGER PRIMARY KEY AUTOINCREMENT,
        symbol               TEXT    NOT NULL UNIQUE,
        shares_outstanding INTEGER NOT NULL,
        price              REAL    NOT NULL,
        currency_id        INTEGER NOT NULL,
        FOREIGN KEY (currency_id) REFERENCES currencies(id)
    );

    CREATE TABLE IF NOT EXISTS periods (
        id         INTEGER PRIMARY KEY AUTOINCREMENT,
        type       TEXT    NOT NULL CHECK(type IN ('Q', 'H', 'Y')),
        year       INTEGER NOT NULL,
        idx        INTEGER NOT NULL,
        start_date TEXT    NOT NULL,
        end_date   TEXT    NOT NULL,
        UNIQUE(type, year, idx)
    );

    CREATE TABLE IF NOT EXISTS category (
        id         INTEGER PRIMARY KEY AUTOINCREMENT,
        company_id INTEGER NOT NULL,
        parent_id  INTEGER,
        name       TEXT    NOT NULL,
        FOREIGN KEY (company_id) REFERENCES companies(id),
        FOREIGN KEY (parent_id)  REFERENCES category(id),
        UNIQUE(company_id, name)
    );

    -- parent table
    CREATE TABLE closed_positions (
        id            INTEGER PRIMARY KEY AUTOINCREMENT,
        symbol        TEXT NOT NULL,
        currency_code TEXT NOT NULL,
        product       TEXT NOT NULL,
        open_time     DATETIME NOT NULL,
        realized_gain REAL,
        tax_amount    REAL,
        holding_days  INTEGER
    );

    -- child table, one row per close lot
    CREATE TABLE close_entries (
        id                  INTEGER PRIMARY KEY AUTOINCREMENT,
        closed_position_id  INTEGER NOT NULL REFERENCES closed_positions(id),
        shares              INTEGER NOT NULL,
        in_price            REAL NOT NULL,
        out_price           REAL NOT NULL,
        gain_price          REAL NOT NULL,
        close_time          DATETIME NOT NULL
    );

    CREATE TABLE IF NOT EXISTS revenue_entries (
        id          INTEGER PRIMARY KEY AUTOINCREMENT,
        company_id  INTEGER NOT NULL,
        currency_id INTEGER NOT NULL,
        category_id INTEGER NOT NULL,
        period_id   INTEGER NOT NULL,
        value       REAL    NOT NULL,
        FOREIGN KEY (company_id)  REFERENCES companies(id),
        FOREIGN KEY (currency_id) REFERENCES currencies(id),
        FOREIGN KEY (category_id) REFERENCES category(id),
        FOREIGN KEY (period_id)   REFERENCES periods(id),
        UNIQUE(company_id, category_id, period_id)
    );`

	if _, err := db.Exec(schema); err != nil {
		log.Fatal("Failed to create tables:", err)
	}
	fmt.Println("Tables ready")
}
