# DO NOT COPY OR SHARE - A3Tech / NCTI course material for enrolled students only.
# shop_db.py - Mama J's shop database helper (Module 6)
#
# Keep this file in the SAME folder as your own programs, then:
#     import shop_db
#
# You don't need to understand everything in here yet - just call the functions.
# The SQL marked (SQL level-up) is what you'll learn to write yourself
# in the SQL level-up course.

import sqlite3

DB_FILE = "shop.db"     # the database is just this one file, next to your programs

STARTER_PRODUCTS = [
    ("Beef Patty", 5.00, 40),
    ("Cheese Patty", 5.00, 30),
    ("Coconut Tart", 4.00, 25),
    ("Sorrel Drink", 3.50, 20),
]


# ---------- the two basic tools: ask a question, or make a change ----------

def query(sql, values=()):
    """Run a SELECT. Gives back the rows as a list of dictionaries."""
    db = sqlite3.connect(DB_FILE)
    db.row_factory = sqlite3.Row
    rows = [dict(row) for row in db.execute(sql, values)]
    db.close()
    return rows


def run(sql, values=()):
    """Run an INSERT, UPDATE or DELETE, and save (commit) the change to shop.db."""
    db = sqlite3.connect(DB_FILE)
    db.execute(sql, values)
    db.commit()
    db.close()


# ---------- ready-made jobs for the shop ----------

def setup():
    """Create the tables and the starter products. Safe to run every time."""
    run("""CREATE TABLE IF NOT EXISTS products (
               id INTEGER PRIMARY KEY, name TEXT UNIQUE, price REAL, stock INTEGER)""")
    run("""CREATE TABLE IF NOT EXISTS sales (
               id INTEGER PRIMARY KEY, day TEXT, product_id INTEGER, qty INTEGER)""")
    for name, price, stock in STARTER_PRODUCTS:
        run("INSERT OR IGNORE INTO products (name, price, stock) VALUES (?, ?, ?)",
            (name, price, stock))


def get_products():
    """Every product, A to Z, as a list of dictionaries."""
    return query("SELECT id, name, price, stock FROM products ORDER BY name")


def find_product(name):
    """One product as a dictionary, or None if the shop doesn't sell it."""
    rows = query("SELECT id, name, price, stock FROM products WHERE name = ?", (name,))
    if rows:
        return rows[0]
    return None


def add_product(name, price, stock):
    """Add a new product. Gives back a message saying what happened."""
    if find_product(name):
        return f"{name} is already in the shop."
    run("INSERT INTO products (name, price, stock) VALUES (?, ?, ?)", (name, price, stock))
    return f"Added {name}."


def record_sale(name, qty):
    """Sell qty of a product: saves the sale and takes the stock down. Gives back a message."""
    product = find_product(name)
    if product is None:
        return f"Sorry, we don't sell {name}."
    if qty > product["stock"]:
        return f"Only {product['stock']} {name} left."
    run("INSERT INTO sales (day, product_id, qty) VALUES (date('now'), ?, ?)",
        (product["id"], qty))
    run("UPDATE products SET stock = stock - ? WHERE id = ?", (qty, product["id"]))
    total = qty * product["price"]
    return f"Sold {qty} x {name} = EC${total:.2f}. {product['stock'] - qty} left."


def sales_report():
    """(SQL level-up) How many of each product sold and the money taken, best seller first."""
    return query("""SELECT p.name AS name, SUM(s.qty) AS qty, SUM(s.qty * p.price) AS money
                    FROM sales s JOIN products p ON p.id = s.product_id
                    GROUP BY p.name
                    ORDER BY money DESC""")


def reset():
    """Empty the shop and start again with just the starter products."""
    run("DROP TABLE IF EXISTS sales")
    run("DROP TABLE IF EXISTS products")
    setup()
