// src/services/userService.ts
import * as db from './db/index.db';
import type { Logger } from 'pino';
import { AddressRepository } from './db/address.db';
import { UserRepository } from './db/user.db';
import type { Address, UserProfile } from '../types';

/**
 * Encapsulates user-related business logic that may involve multiple repository calls.
 */
class UserService {
  /**
   * Per ADR-002, this function encapsulates a multi-write operation within a transaction.
   * It creates or updates a user's address and links it to their profile atomically.
   *
   * @param user The user profile object.
   * @param addressData The address data to upsert.
   * @returns The ID of the upserted address.
   */
  async upsertUserAddress(user: UserProfile, addressData: Partial<Address>, logger: Logger): Promise<number> {
    return db.withTransaction(async (client) => {
      // Instantiate repositories with the transactional client
      const addressRepo = new AddressRepository(client);
      const userRepo = new UserRepository(client);

      const addressId = await addressRepo.upsertAddress({ ...addressData, address_id: user.address_id ?? undefined }, logger);

      // If the user didn't have an address_id before, update their profile to link it.
      if (!user.address_id) {
        await userRepo.updateUserProfile(user.user_id, { address_id: addressId }, logger);
      }

      return addressId;
    });
  }
}

export const userService = new UserService();