/**
 * Address query helpers.
 *
 * All functions take DrizzleClient as first arg per project convention.
 * IDOR safety: every write helper requires userId to scope operations.
 */

import { and, eq } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import { addresses } from '../schema.js';

export type CreateAddressInput = typeof addresses.$inferInsert;

export async function createAddress(
  db: DrizzleClient,
  values: CreateAddressInput,
): Promise<void> {
  await db.insert(addresses).values(values);
}

/**
 * Unset isDefault on all addresses belonging to a user.
 * Call this before setting a new default to maintain a single-default invariant.
 */
export async function clearDefaultAddresses(db: DrizzleClient, userId: string): Promise<void> {
  await db.update(addresses).set({ isDefault: false }).where(eq(addresses.userId, userId));
}

/**
 * Delete an address by id, scoped to the owning user (IDOR-safe).
 *
 * Returns true if the address was found and deleted; false if not found
 * (not owned by this user or does not exist).
 */
export async function deleteAddress(
  db: DrizzleClient,
  id: string,
  userId: string,
): Promise<boolean> {
  const result = await db
    .delete(addresses)
    .where(and(eq(addresses.id, id), eq(addresses.userId, userId)))
    .returning({ id: addresses.id });
  return result.length > 0;
}
