import { prisma } from "@/lib/prisma";
import { SocialPlatform } from "@/lib/social-platforms";

const DEFAULTS = {
  address: "123 Main Street, Suite 4, Your City, ST 00000",
  phone: "(555) 123-4567",
  hours: "Mon – Sat: 9:00am – 6:00pm\nSunday: Closed",
};

export type BusinessSettings = {
  address: string;
  phone: string;
  hours: string;
  coords: { lat: number; lng: number } | null;
  social: Record<SocialPlatform, { enabled: boolean; url: string }>;
};

export async function getBusinessSettings(): Promise<BusinessSettings> {
  const settings = await prisma.settings.findUnique({ where: { id: "singleton" } });

  const hasCustomAddress = Boolean(settings?.businessAddress?.trim());

  return {
    address: settings?.businessAddress?.trim() || DEFAULTS.address,
    phone: settings?.businessPhone?.trim() || DEFAULTS.phone,
    hours: settings?.businessHours?.trim() || DEFAULTS.hours,
    coords:
      hasCustomAddress && settings?.businessLat != null && settings?.businessLng != null
        ? { lat: settings.businessLat, lng: settings.businessLng }
        : null,
    social: {
      instagram: {
        enabled: settings?.instagramEnabled ?? false,
        url: settings?.instagramUrl ?? "",
      },
      facebook: {
        enabled: settings?.facebookEnabled ?? false,
        url: settings?.facebookUrl ?? "",
      },
      tiktok: {
        enabled: settings?.tiktokEnabled ?? false,
        url: settings?.tiktokUrl ?? "",
      },
      youtube: {
        enabled: settings?.youtubeEnabled ?? false,
        url: settings?.youtubeUrl ?? "",
      },
    },
  };
}

export function mapsDirectionsUrl(address: string) {
  return `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(address)}`;
}

export function mapsEmbedUrl(address: string) {
  const key = process.env.GOOGLE_MAPS_EMBED_KEY;
  if (!key) return null;
  return `https://www.google.com/maps/embed/v1/place?key=${key}&q=${encodeURIComponent(address)}`;
}

// No-API-key fallback: OpenStreetMap's embeddable iframe, centered on
// coordinates resolved by the free Nominatim geocoder when the admin saves
// their address (see src/lib/geocode.ts).
export function osmEmbedUrl(coords: { lat: number; lng: number }) {
  const delta = 0.006;
  const bbox = [
    coords.lng - delta,
    coords.lat - delta,
    coords.lng + delta,
    coords.lat + delta,
  ].join(",");
  return `https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=mapnik&marker=${coords.lat},${coords.lng}`;
}
