import { type APIRequestContext } from '@playwright/test';

/** Creates a valid listing payload for E2E tests. */
export function createTestListing(overrides: Record<string, unknown> = {}) {
  const suffix = Date.now();
  return {
    transactionType: 'SALE',
    propertyType: 'APARTMENT',
    title: `Test Listing ${suffix}`,
    description: `E2E test listing description for automated testing ${suffix}`,
    address: '123 Nguyễn Huệ',
    ward: 'Bến Nghé',
    district: 'Quận 1',
    city: 'Hồ Chí Minh',
    latitude: 10.7769,
    longitude: 106.7009,
    areaM2: 75,
    priceVND: '5000000000',
    bedrooms: 2,
    bathrooms: 2,
    floors: 1,
    direction: 'SOUTH',
    ...overrides,
  };
}

/** Creates a listing via the API and returns its response + original data. */
export async function createListing(
  request: APIRequestContext,
  accessToken: string,
  overrides: Record<string, unknown> = {},
) {
  const data = createTestListing(overrides);
  const res = await request.post('listings', {
    data,
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  if (!res.ok()) {
    const body = await res.text();
    throw new Error(`Create listing failed (${res.status()}): ${body}`);
  }
  return { listing: await res.json(), data };
}
