from database.connection import get_db

PAGE_SIZE = 8


async def create_ticket(org_id: int, created_by: int, description: str) -> int:
    db = get_db()
    async with db.execute(
        "INSERT INTO tickets (org_id, created_by, description) VALUES (?, ?, ?)",
        (org_id, created_by, description),
    ) as cur:
        ticket_id = cur.lastrowid
    await db.commit()
    return ticket_id


async def get_ticket(ticket_id: int) -> dict | None:
    db = get_db()
    async with db.execute(
        """
        SELECT t.*, bu.first_name as author_name, bu.username as author_username
        FROM tickets t
        LEFT JOIN bot_users bu ON bu.id = t.created_by
        WHERE t.id = ?
        """,
        (ticket_id,),
    ) as cur:
        row = await cur.fetchone()
    return dict(row) if row else None


async def get_tickets_for_org(org_id: int, page: int = 0) -> list[dict]:
    db = get_db()
    offset = page * PAGE_SIZE
    async with db.execute(
        """
        SELECT id, description, status, created_at, last_comment
        FROM tickets
        WHERE org_id = ?
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
        """,
        (org_id, PAGE_SIZE, offset),
    ) as cur:
        rows = await cur.fetchall()
    return [dict(r) for r in rows]


async def count_tickets_for_org(org_id: int) -> int:
    db = get_db()
    async with db.execute(
        "SELECT COUNT(*) FROM tickets WHERE org_id = ?", (org_id,)
    ) as cur:
        row = await cur.fetchone()
    return row[0] if row else 0


async def get_all_tickets(
    org_id: int | None = None, status: str | None = None
) -> list[dict]:
    db = get_db()
    conditions = []
    params: list = []
    if org_id is not None:
        conditions.append("t.org_id = ?")
        params.append(org_id)
    if status is not None:
        conditions.append("t.status = ?")
        params.append(status)
    where = ("WHERE " + " AND ".join(conditions)) if conditions else ""
    query = f"""
        SELECT t.*, o.name as org_name, bu.first_name as author_name
        FROM tickets t
        LEFT JOIN organizations o ON o.id = t.org_id
        LEFT JOIN bot_users bu ON bu.id = t.created_by
        {where}
        ORDER BY t.created_at DESC
    """
    async with db.execute(query, params) as cur:
        rows = await cur.fetchall()
    return [dict(r) for r in rows]


async def update_ticket_status(
    ticket_id: int, status: str, last_comment: str | None
) -> None:
    db = get_db()
    await db.execute(
        """
        UPDATE tickets
        SET status = ?, last_comment = COALESCE(?, last_comment),
            updated_at = datetime('now')
        WHERE id = ?
        """,
        (status, last_comment, ticket_id),
    )
    await db.commit()
