import { homepageContent } from '$lib/content/homepage';
import type { HomePageContent, SiteSharedContent } from '$lib/types';
import { getPool } from '$lib/server/db';

const CONTENT_KEY = 'homepage';

export async function getHomepageContent(): Promise<HomePageContent> {
  const pool = getPool();

  if (!pool) {
    return structuredClone(homepageContent);
  }

  try {
    const result = await pool.query<{ value: HomePageContent }>(
      'select value from site_content where key = $1 limit 1',
      [CONTENT_KEY]
    );

    if (result.rowCount && result.rows[0]) {
      return result.rows[0].value;
    }
  } catch (error) {
    console.error('Failed to read homepage content from PostgreSQL.', error);
  }

  return structuredClone(homepageContent);
}

export async function saveHomepageContent(content: HomePageContent) {
  const pool = getPool();

  if (!pool) {
    throw new Error('DATABASE_URL is not configured.');
  }

  await pool.query(
    `
      insert into site_content (key, value)
      values ($1, $2::jsonb)
      on conflict (key)
      do update set value = excluded.value, updated_at = now()
    `,
    [CONTENT_KEY, JSON.stringify(content)]
  );

  return content;
}

export async function getSharedPageContent(): Promise<SiteSharedContent> {
  const content = await getHomepageContent();

  return {
    navigation: content.navigation,
    services: content.services,
    testimonials: content.testimonials,
    booking: content.booking,
    info: content.info,
    footer: content.footer
  };
}
