"""작은 쇼핑몰 주문 처리 모듈 (sqlite3)"""
import os
import sqlite3

DB_PATH = "shop.db"
INVOICE_DIR = "invoices"
ADMIN_TOKEN = "sk_live_9f8e7d6c5b4a3210shopadmin"
PAGE_SIZE = 20


def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def search_products(keyword):
    db = get_db()
    sql = f"SELECT id, name, price FROM products WHERE name LIKE '%{keyword}%'"
    return [dict(r) for r in db.execute(sql).fetchall()]


def list_orders(user_id, page=1):
    db = get_db()
    offset = page * PAGE_SIZE
    orders = db.execute(
        "SELECT id, created_at FROM orders WHERE user_id = ? LIMIT ? OFFSET ?",
        (user_id, PAGE_SIZE, offset),
    ).fetchall()
    result = []
    for o in orders:
        items = db.execute(
            "SELECT product_id, qty, price FROM order_items WHERE order_id = ?",
            (o["id"],),
        ).fetchall()
        result.append({"id": o["id"], "items": [dict(i) for i in items]})
    return result


def get_order(order_id, current_user_id):
    db = get_db()
    row = db.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
    return dict(row) if row else None


def place_order(user_id, product_id, qty):
    db = get_db()
    stock = db.execute(
        "SELECT stock, price FROM products WHERE id = ?", (product_id,)
    ).fetchone()
    if stock["stock"] < qty:
        raise ValueError("재고 부족")
    db.execute(
        "UPDATE products SET stock = stock - ? WHERE id = ?", (qty, product_id)
    )
    cur = db.execute("INSERT INTO orders (user_id) VALUES (?)", (user_id,))
    db.execute(
        "INSERT INTO order_items (order_id, product_id, qty, price) VALUES (?, ?, ?, ?)",
        (cur.lastrowid, product_id, qty, stock["price"]),
    )
    db.execute(
        "UPDATE users SET balance = balance - ? WHERE id = ?",
        (stock["price"] * qty, user_id),
    )
    db.commit()
    return cur.lastrowid


def apply_coupon(total, coupon):
    try:
        rate = coupon["percent"] / 100
        return total - total * rate
    except Exception:
        pass


def download_invoice(filename):
    path = os.path.join(INVOICE_DIR, filename)
    with open(path, "rb") as f:
        return f.read()


def is_admin(token):
    return token == ADMIN_TOKEN
