import { getDatabase } from '../index';
import { UserListItem, UserListType } from '../../../types';
import { generateUUID } from '../../utils/uuid';
import { now } from '../../utils/datetime';

export async function createListItem(
  userId: string,
  type: UserListType,
  item: string,
  notes?: string
): Promise<UserListItem> {
  const db = getDatabase();
  const id = generateUUID();

  await db.runAsync(
    `INSERT INTO user_lists (id, user_id, type, item, notes, is_completed, created_at)
     VALUES (?, ?, ?, ?, ?, 0, ?)`,
    [id, userId, type, item, notes || null, now()]
  );

  return {
    id,
    userId,
    type,
    item,
    notes,
    isCompleted: false,
    createdAt: now(),
  };
}

export async function getListItems(userId: string, type: UserListType): Promise<UserListItem[]> {
  const db = getDatabase();
  const rows = await db.getAllAsync<any>(
    'SELECT * FROM user_lists WHERE user_id = ? AND type = ? ORDER BY is_completed ASC, created_at DESC',
    [userId, type]
  );

  return rows.map(row => ({
    id: row.id,
    userId: row.user_id,
    type: row.type,
    item: row.item,
    notes: row.notes || undefined,
    isCompleted: row.is_completed === 1,
    createdAt: row.created_at,
  }));
}

export async function updateListItem(id: string, updates: Partial<UserListItem>): Promise<void> {
  const db = getDatabase();

  if (updates.item !== undefined) {
    await db.runAsync(
      'UPDATE user_lists SET item = ? WHERE id = ?',
      [updates.item, id]
    );
  }

  if (updates.notes !== undefined) {
    await db.runAsync(
      'UPDATE user_lists SET notes = ? WHERE id = ?',
      [updates.notes || null, id]
    );
  }

  if (updates.isCompleted !== undefined) {
    await db.runAsync(
      'UPDATE user_lists SET is_completed = ? WHERE id = ?',
      [updates.isCompleted ? 1 : 0, id]
    );
  }
}

export async function deleteListItem(id: string): Promise<void> {
  const db = getDatabase();
  await db.runAsync('DELETE FROM user_lists WHERE id = ?', [id]);
}

export async function toggleListItemCompleted(id: string): Promise<void> {
  const db = getDatabase();
  await db.runAsync(
    'UPDATE user_lists SET is_completed = 1 - is_completed WHERE id = ?',
    [id]
  );
}
