import "server-only";

import { cache } from "react";
import {
  blogPosts as mockBlogPosts,
  faqItems as mockFaqItems,
  properties as mockProperties,
  regions as mockRegions,
} from "@/data/mockData";
import type { BlogPost, FAQItem, Property, Region } from "@/data/types";
import { query } from "@/lib/db";
import { stripHtml } from "@/lib/rich-text";
import type { FooterPageLink, FooterRegionLink } from "@/lib/site-data";

type PropertyRow = {
  address_text: string | null;
  area_total: number | null;
  bathrooms_count: number | null;
  bedrooms_count: number | null;
  currency_code: string;
  deal_type_code: "sale" | "rent" | "investment";
  floor_number: number | null;
  floors_total: number | null;
  grand_name: string | null;
  grand_slug: string | null;
  grand_type: string | null;
  great_name: string | null;
  great_slug: string | null;
  great_type: string | null;
  is_featured: boolean;
  is_luxury: boolean;
  is_new_build: boolean;
  latitude: number | null;
  loc_name: string | null;
  loc_slug: string | null;
  loc_type: string | null;
  longitude: number | null;
  office_address: string | null;
  office_email: string | null;
  office_name: string | null;
  office_phone: string | null;
  parent_name: string | null;
  parent_slug: string | null;
  parent_type: string | null;
  price: number | null;
  property_type_name: string;
  published_at: string | null;
  ref_number: string;
  seo_description: string | null;
  seo_title: string | null;
  status_code: string;
  title: string;
  description: string;
  year_built: number | null;
};

type PropertyMediaRow = {
  file_url: string;
  ref_number: string;
};

type PropertyFeatureRow = {
  feature: string | null;
  ref_number: string;
};

type PropertyHighlightRow = {
  icon_name: string | null;
  label: string;
  ref_number: string;
  sort_order: number;
  value_text: string;
};

type BlogRow = {
  author_name: string | null;
  categories: string[] | null;
  content: string;
  excerpt: string | null;
  featured_image_url: string | null;
  id: string;
  published_at: string | null;
  slug: string;
  tags: string[] | null;
  title: string;
};

type FaqRow = {
  answer: string;
  id: string;
  page_title: string | null;
  question: string;
};

type FooterPageRow = {
  code?: string;
  name?: string;
  slug: string;
  title?: string;
};

type FooterRegionRow = {
  name: string;
  slug: string;
};

type PublishedPageRow = {
  content: string;
  excerpt: string | null;
  robots_meta: string | null;
  seo_description: string | null;
  seo_title: string | null;
  slug: string;
  title: string;
};

const defaultPropertyImage =
  "https://images.unsplash.com/photo-1502672260266-1c1ef2d93688?w=1200";

const reservedCustomPageSlugs = new Set([
  "about",
  "admin",
  "api",
  "blog",
  "contact",
  "evaluate",
  "faq",
  "favorites",
  "login",
  "my-inquiries",
  "profile",
  "properties",
  "register",
  "robots.txt",
  "search",
  "sitemap.xml",
]);

const fallbackSystemFooterPages: FooterPageLink[] = [
  { label: "Имоти", path: "/properties", slug: "properties" },
  { label: "Продажби", path: "/properties?deal=sale", slug: "sale" },
  { label: "Наеми", path: "/properties?deal=rent", slug: "rent" },
];

function formatFooterDealTypeLabel(code: string, name: string) {
  if (code === "sale") {
    return "Продажби";
  }

  if (code === "rent") {
    return "Наеми";
  }

  if (code === "investment") {
    return "Инвестиции";
  }

  return name;
}

function usesLocalDatabase() {
  if (process.env.DATABASE_URL) {
    return /(?:localhost|127\.0\.0\.1)/.test(process.env.DATABASE_URL);
  }

  const host = process.env.PGHOST || "/tmp";
  return host === "127.0.0.1" || host === "localhost" || host === "/tmp";
}

const canUseMockFallback = process.env.NODE_ENV !== "production" || usesLocalDatabase();

function formatDate(dateLike: string | null) {
  if (!dateLike) {
    return new Date().toISOString().slice(0, 10);
  }

  return new Date(dateLike).toISOString().slice(0, 10);
}

function estimateReadTime(text: string) {
  const words = stripHtml(text).trim().split(/\s+/).filter(Boolean).length;
  return Math.max(1, Math.ceil(words / 180));
}

function isDatabaseUnavailableError(error: unknown) {
  if (!(error instanceof Error)) {
    return false;
  }

  const pgError = error as NodeJS.ErrnoException & { cause?: NodeJS.ErrnoException };
  const code = pgError.code || pgError.cause?.code;
  const message = error.message.toLowerCase();

  return (
    code === "ECONNREFUSED" ||
    code === "EPERM" ||
    code === "ENOENT" ||
    code === "ETIMEDOUT" ||
    message.includes("connect econnrefused") ||
    message.includes("connect eperm") ||
    message.includes("database") && message.includes("does not exist")
  );
}

async function withMockFallback<T>(
  label: string,
  load: () => Promise<T>,
  fallback: () => T,
): Promise<T> {
  try {
    return await load();
  } catch (error) {
    if (!canUseMockFallback || !isDatabaseUnavailableError(error)) {
      throw error;
    }

    console.warn(`[db-content] ${label} falling back to mock content because PostgreSQL is unavailable.`, error);
    return fallback();
  }
}

function normalizeStatus(statusCode: string): Property["status"] {
  if (statusCode === "sold") {
    return "sold";
  }

  if (statusCode === "reserved") {
    return "reserved";
  }

  return "active";
}

function resolveLocation(row: PropertyRow) {
  const nodes = [
    { name: row.loc_name, slug: row.loc_slug, type: row.loc_type },
    { name: row.parent_name, slug: row.parent_slug, type: row.parent_type },
    { name: row.grand_name, slug: row.grand_slug, type: row.grand_type },
    { name: row.great_name, slug: row.great_slug, type: row.great_type },
  ].filter((node) => node.name && node.type);

  const cityNode = nodes.find((node) => node.type === "city");
  const regionNode = nodes.find((node) => node.type === "region");
  const districtNode = nodes.find(
    (node) => node.type === "district" || node.type === "subdistrict",
  );

  return {
    city: cityNode?.name || regionNode?.name || row.loc_name || "Гърция",
    citySlug: cityNode?.slug || regionNode?.slug || row.loc_slug || "greece",
    district: districtNode?.name || undefined,
    lat: Number(row.latitude || 0),
    lng: Number(row.longitude || 0),
    region: regionNode?.name || cityNode?.name || row.loc_name || "Гърция",
    regionSlug: regionNode?.slug || cityNode?.slug || row.loc_slug || "greece",
  };
}

function buildPropertyTags(row: PropertyRow) {
  const tags: string[] = [];

  if (row.is_featured) {
    tags.push("Премиум");
  }

  if (row.is_new_build) {
    tags.push("Нова обява");
  }

  if (row.is_luxury) {
    tags.push("Луксозен");
  }

  if (row.status_code === "reserved") {
    tags.push("Резервиран");
  }

  if (row.status_code === "sold") {
    tags.push("Продаден");
  }

  return tags;
}

const propertyRowsSql = `
  SELECT
    p.ref_number,
    p.title,
    p.description,
    p.price,
    p.currency_code,
    dt.code AS deal_type_code,
    pt.name AS property_type_name,
    p.area_total,
    p.bedrooms_count,
    p.bathrooms_count,
    p.floor_number,
    p.floors_total,
    p.year_built,
    ps.code AS status_code,
    p.is_featured,
    p.is_new_build,
    p.is_luxury,
    p.address_text,
    p.latitude,
    p.longitude,
    o.name AS office_name,
    o.phone AS office_phone,
    o.email AS office_email,
    o.address AS office_address,
    loc.name AS loc_name,
    loc.slug AS loc_slug,
    loc_type.code AS loc_type,
    parent.name AS parent_name,
    parent.slug AS parent_slug,
    parent_type.code AS parent_type,
    grand.name AS grand_name,
    grand.slug AS grand_slug,
    grand_type.code AS grand_type,
    great.name AS great_name,
    great.slug AS great_slug,
    great_type.code AS great_type,
    seo.title_tag AS seo_title,
    seo.meta_description AS seo_description,
    COALESCE(p.published_at, p.created_at) AS published_at
  FROM properties p
  JOIN property_types pt ON pt.id = p.property_type_id
  JOIN deal_types dt ON dt.id = p.deal_type_id
  JOIN property_statuses ps ON ps.id = p.status_id
  LEFT JOIN offices o ON o.id = p.office_id
  LEFT JOIN locations loc ON loc.id = p.location_id
  LEFT JOIN location_types loc_type ON loc_type.id = loc.location_type_id
  LEFT JOIN locations parent ON parent.id = loc.parent_id
  LEFT JOIN location_types parent_type ON parent_type.id = parent.location_type_id
  LEFT JOIN locations grand ON grand.id = parent.parent_id
  LEFT JOIN location_types grand_type ON grand_type.id = grand.location_type_id
  LEFT JOIN locations great ON great.id = grand.parent_id
  LEFT JOIN location_types great_type ON great_type.id = great.location_type_id
  LEFT JOIN seo_metadata seo
    ON seo.entity_type = 'property'
    AND seo.entity_id = p.id
  WHERE p.deleted_at IS NULL
    AND p.is_active = true
    AND ps.code IN ('active', 'reserved', 'sold')
  ORDER BY COALESCE(p.published_at, p.created_at) DESC, p.ref_number DESC
`;

const propertyMediaSql = `
  SELECT p.ref_number, pm.file_url
  FROM property_media pm
  JOIN properties p ON p.id = pm.property_id
  JOIN media_types mt ON mt.id = pm.media_type_id
  WHERE mt.code = 'image'
  ORDER BY p.ref_number, pm.is_cover DESC, pm.sort_order ASC, pm.created_at ASC
`;

const propertyFeaturesSql = `
  SELECT
    p.ref_number,
    CASE
      WHEN cfd.field_type = 'boolean' AND pcfv.value_boolean IS TRUE THEN cfd.label
      WHEN cfd.field_type IN ('select', 'radio', 'checkbox') AND cfo.value_label IS NOT NULL THEN cfd.label || ': ' || cfo.value_label
      WHEN cfd.field_type = 'number' AND pcfv.value_number IS NOT NULL THEN cfd.label || ': ' || trim(trailing '.00' FROM pcfv.value_number::text)
      WHEN cfd.field_type = 'date' AND pcfv.value_date IS NOT NULL THEN cfd.label || ': ' || pcfv.value_date::text
      WHEN pcfv.value_text IS NOT NULL AND pcfv.value_text <> '' THEN cfd.label || ': ' || pcfv.value_text
      ELSE NULL
    END AS feature
  FROM property_custom_field_values pcfv
  JOIN properties p ON p.id = pcfv.property_id
  JOIN custom_field_definitions cfd ON cfd.id = pcfv.field_definition_id
  LEFT JOIN custom_field_options cfo ON cfo.id = pcfv.value_option_id
  WHERE cfd.is_active = true
    AND cfd.is_visible_in_detail = true

  UNION ALL

  SELECT
    p.ref_number,
    cfd.label || ': ' || cfo.value_label AS feature
  FROM property_custom_field_multi_values pcmv
  JOIN properties p ON p.id = pcmv.property_id
  JOIN custom_field_definitions cfd ON cfd.id = pcmv.field_definition_id
  JOIN custom_field_options cfo ON cfo.id = pcmv.option_id
  WHERE cfd.is_active = true
    AND cfd.is_visible_in_detail = true
`;

const propertyHighlightsSql = `
  SELECT
    p.ref_number,
    pfi.label,
    pfi.value_text,
    pfi.icon_name,
    pfi.sort_order
  FROM property_feature_items pfi
  JOIN properties p ON p.id = pfi.property_id
  ORDER BY p.ref_number, pfi.sort_order ASC, pfi.created_at ASC
`;

export const getPublicProperties = cache(async (): Promise<Property[]> =>
  withMockFallback(
    "getPublicProperties",
    async () => {
      const [propertyResult, mediaResult, featureResult, highlightResult] = await Promise.all([
        query<PropertyRow>(propertyRowsSql),
        query<PropertyMediaRow>(propertyMediaSql),
        query<PropertyFeatureRow>(propertyFeaturesSql),
        query<PropertyHighlightRow>(propertyHighlightsSql),
      ]);

      const mediaMap = new Map<string, string[]>();
      for (const row of mediaResult.rows) {
        const images = mediaMap.get(row.ref_number) || [];
        images.push(row.file_url);
        mediaMap.set(row.ref_number, images);
      }

      const featureMap = new Map<string, string[]>();
      for (const row of featureResult.rows) {
        if (!row.feature) {
          continue;
        }

        const features = featureMap.get(row.ref_number) || [];
        if (!features.includes(row.feature)) {
          features.push(row.feature);
        }
        featureMap.set(row.ref_number, features);
      }

      const highlightMap = new Map<
        string,
        Array<{ iconName?: string; label: string; value: string }>
      >();
      for (const row of highlightResult.rows) {
        const items = highlightMap.get(row.ref_number) || [];
        items.push({
          iconName: row.icon_name || undefined,
          label: row.label,
          value: row.value_text,
        });
        highlightMap.set(row.ref_number, items);
      }

      return propertyResult.rows.map((row) => {
        const location = resolveLocation(row);
        const featureList = [...(featureMap.get(row.ref_number) || [])];

        if (row.is_new_build && !featureList.includes("Ново строителство")) {
          featureList.unshift("Ново строителство");
        }

        if (row.is_luxury && !featureList.includes("Луксозен клас")) {
          featureList.unshift("Луксозен клас");
        }

        return {
          area: Number(row.area_total || 0),
          bathrooms: Number(row.bathrooms_count || 0),
          bedrooms: Number(row.bedrooms_count || 0),
          broker: row.office_name || "office",
          createdAt: formatDate(row.published_at),
          currency: row.currency_code,
          dealType: row.deal_type_code === "rent" ? "rent" : "sale",
          description: row.description,
          featured: row.is_featured,
          features: featureList,
          floor: row.floor_number ?? undefined,
          id: row.ref_number,
          images: mediaMap.get(row.ref_number) || [defaultPropertyImage],
          highlights: highlightMap.get(row.ref_number) || [],
          location: {
            address: row.address_text || row.office_address || undefined,
            city: location.city,
            district: location.district,
            lat: location.lat,
            lng: location.lng,
            region: location.region,
          },
          office: {
            address: row.office_address || "",
            email: row.office_email || "",
            name: row.office_name || "",
            phone: row.office_phone || "",
          },
          price: Number(row.price || 0),
          propertyType: row.property_type_name,
          seoDescription: row.seo_description || undefined,
          seoTitle: row.seo_title || undefined,
          status: normalizeStatus(row.status_code),
          tags: buildPropertyTags(row),
          title: row.title,
          totalFloors: row.floors_total ?? undefined,
          yearBuilt: row.year_built ?? undefined,
        };
      });
    },
    () => mockProperties,
  ),
);

export const getPropertyById = cache(async (id: string) => {
  const properties = await getPublicProperties();
  return properties.find((property) => property.id === id);
});

export const getFeaturedProperties = cache(async () => {
  const properties = await getPublicProperties();
  return properties.filter((property) => property.featured).slice(0, 4);
});

export const getPropertyTypes = cache(async () => {
  const properties = await getPublicProperties();
  return [...new Set(properties.map((property) => property.propertyType))];
});

export const getPropertyRegions = cache(async () => {
  const properties = await getPublicProperties();
  return [
    ...new Set(
      properties.flatMap((property) => [property.location.region, property.location.city]),
    ),
  ].filter(Boolean);
});

export const getTopRegions = cache(async (): Promise<Region[]> =>
  withMockFallback(
    "getTopRegions",
    async () => {
      const result = await query<{
        description: string | null;
        id: string;
        image_url: string | null;
        name: string;
        property_count: string;
        slug: string;
        sort_order: number;
      }>(`
        WITH RECURSIVE region_nodes AS (
          SELECT
            l.id AS region_id,
            l.id AS location_id
          FROM locations l
          JOIN location_types lt ON lt.id = l.location_type_id
          WHERE lt.code = 'region'
            AND l.is_active = true

          UNION ALL

          SELECT
            rn.region_id,
            child.id AS location_id
          FROM region_nodes rn
          JOIN locations child ON child.parent_id = rn.location_id
          WHERE child.is_active = true
        )
        SELECT
          region.id::text,
          region.name,
          region.slug,
          region.description,
          region.image_url,
          region.sort_order,
          COUNT(DISTINCT p.id)::text AS property_count
        FROM locations region
        JOIN location_types lt ON lt.id = region.location_type_id
        LEFT JOIN region_nodes rn ON rn.region_id = region.id
        LEFT JOIN properties p
          ON p.location_id = rn.location_id
         AND p.deleted_at IS NULL
         AND p.is_active = true
        LEFT JOIN property_statuses ps ON ps.id = p.status_id
        WHERE lt.code = 'region'
          AND region.is_active = true
          AND (ps.code IS NULL OR ps.code IN ('active', 'reserved', 'sold'))
        GROUP BY region.id
        ORDER BY region.sort_order ASC, COUNT(DISTINCT p.id) DESC, region.name ASC
        LIMIT 6
      `);

      return result.rows.map((row) => ({
        description:
          stripHtml(row.description || "").trim() ||
          `Разгледайте актуалните предложения за имоти в ${row.name}.`,
        id: row.id,
        image: row.image_url || defaultPropertyImage,
        name: row.name,
        propertyCount: Number(row.property_count || 0),
        slug: row.slug,
      }));
    },
    () => mockRegions.slice(0, 6),
  ),
);

export const getFooterPages = cache(async (): Promise<FooterPageLink[]> =>
  withMockFallback(
    "getFooterPages",
    async () => {
      const [dealTypeResult, pageResult] = await Promise.all([
        query<FooterPageRow>(`
          SELECT
            dt.code,
            dt.name,
            dt.slug
          FROM deal_types dt
          WHERE dt.is_active = true
            AND dt.code IN ('sale', 'rent', 'investment')
          ORDER BY
            CASE dt.code
              WHEN 'sale' THEN 1
              WHEN 'rent' THEN 2
              WHEN 'investment' THEN 3
              ELSE 99
            END,
            dt.name ASC
        `),
        query<FooterPageRow>(`
        SELECT
          p.title,
          p.slug
        FROM pages p
        WHERE p.deleted_at IS NULL
          AND p.is_published = true
        ORDER BY p.title ASC
      `),
      ]);

      const systemPages: FooterPageLink[] = [
        {
          label: "Имоти",
          path: "/properties",
          slug: "properties",
        },
        ...dealTypeResult.rows.map((row) => ({
          label: formatFooterDealTypeLabel(row.code || "", row.name || row.title),
          path: `/properties?deal=${encodeURIComponent(row.code || row.slug)}`,
          slug: row.code || row.slug,
        })),
      ];

      const customPages = pageResult.rows
        .filter((row) => row.slug && !reservedCustomPageSlugs.has(row.slug))
        .map((row) => ({
          label: row.title,
          path: `/${row.slug}`,
          slug: row.slug,
        }));

      return [...systemPages, ...customPages];
    },
    () => fallbackSystemFooterPages,
  ),
);

export const getFooterRegions = cache(async (): Promise<FooterRegionLink[]> =>
  withMockFallback(
    "getFooterRegions",
    async () => {
      const result = await query<FooterRegionRow>(`
        SELECT
          l.name,
          l.slug
        FROM locations l
        JOIN location_types lt ON lt.id = l.location_type_id
        WHERE lt.code = 'region'
          AND l.is_active = true
        ORDER BY l.sort_order ASC, l.name ASC
      `);

      return result.rows.map((row) => ({
        label: row.name,
        path: `/properties?region=${encodeURIComponent(row.name)}`,
        slug: row.slug,
      }));
    },
    () => [],
  ),
);

export const getPublishedCustomPageSlugs = cache(async (): Promise<string[]> =>
  withMockFallback(
    "getPublishedCustomPageSlugs",
    async () => {
      const result = await query<{ slug: string }>(`
        SELECT p.slug
        FROM pages p
        WHERE p.deleted_at IS NULL
          AND p.is_published = true
        ORDER BY p.slug ASC
      `);

      return result.rows
        .map((row) => row.slug)
        .filter((slug) => slug && !reservedCustomPageSlugs.has(slug));
    },
    () => [],
  ),
);

export const getPublishedCustomPageBySlug = cache(async (slug: string) =>
  withMockFallback(
    "getPublishedCustomPageBySlug",
    async () => {
      if (!slug || reservedCustomPageSlugs.has(slug)) {
        return null;
      }

      const result = await query<PublishedPageRow>(
        `
          SELECT
            p.title,
            p.slug,
            p.content,
            p.excerpt,
            seo.title_tag AS seo_title,
            seo.meta_description AS seo_description,
            seo.robots_meta
          FROM pages p
          LEFT JOIN seo_metadata seo
            ON seo.entity_type = 'page'
           AND seo.entity_id = p.id
          WHERE p.slug = $1
            AND p.deleted_at IS NULL
            AND p.is_published = true
          LIMIT 1
        `,
        [slug],
      );

      const row = result.rows[0];

      if (!row) {
        return null;
      }

      const plainExcerpt = stripHtml(row.excerpt || row.content).trim();

      return {
        content: row.content,
        description: row.seo_description || plainExcerpt.slice(0, 160),
        noIndex: row.robots_meta?.toLowerCase().includes("noindex") || false,
        slug: row.slug,
        title: row.title,
        titleTag: row.seo_title || row.title,
      };
    },
    () => null,
  ),
);

export const getBlogPosts = cache(async (): Promise<BlogPost[]> =>
  withMockFallback(
    "getBlogPosts",
    async () => {
      const result = await query<BlogRow>(`
        SELECT
          bp.id::text,
          bp.title,
          bp.slug,
          bp.excerpt,
          bp.content,
          bp.author_name,
          bp.featured_image_url,
          bp.published_at,
          array_remove(array_agg(DISTINCT bc.name), NULL) AS categories,
          array_remove(array_agg(DISTINCT bt.name), NULL) AS tags
        FROM blog_posts bp
        LEFT JOIN blog_post_categories bpc ON bpc.blog_post_id = bp.id
        LEFT JOIN blog_categories bc ON bc.id = bpc.category_id
        LEFT JOIN blog_post_tags bpt ON bpt.blog_post_id = bp.id
        LEFT JOIN blog_tags bt ON bt.id = bpt.tag_id
        WHERE bp.deleted_at IS NULL
          AND bp.is_published = true
        GROUP BY bp.id
        ORDER BY bp.published_at DESC NULLS LAST, bp.created_at DESC
      `);

      return result.rows.map((row) => {
        const content = row.content?.trim() || row.excerpt?.trim() || row.title;

        return {
          author: row.author_name || "Редакционен екип",
          category: row.categories?.[0] || "Общи",
          content,
          excerpt: row.excerpt || content,
          id: row.id,
          image: row.featured_image_url || defaultPropertyImage,
          publishedAt: formatDate(row.published_at),
          readTime: estimateReadTime(content),
          slug: row.slug,
          tags: row.tags || [],
          title: row.title,
        };
      });
    },
    () => mockBlogPosts,
  ),
);

export const getBlogPostBySlug = cache(async (slug: string) => {
  const posts = await getBlogPosts();
  return posts.find((post) => post.slug === slug);
});

export const getLatestBlogPosts = cache(async () => {
  const posts = await getBlogPosts();
  return posts.slice(0, 3);
});

export const getFaqItems = cache(async (): Promise<FAQItem[]> =>
  withMockFallback(
    "getFaqItems",
    async () => {
      const result = await query<FaqRow>(`
        SELECT
          f.id::text,
          f.question,
          f.answer,
          p.title AS page_title
        FROM faqs f
        JOIN pages p ON p.id = f.page_id
        WHERE f.is_active = true
          AND p.deleted_at IS NULL
          AND p.is_published = true
        ORDER BY f.sort_order ASC, f.created_at ASC
      `);

      return result.rows.map((row) => ({
        answer: row.answer,
        category: row.page_title || "Общи",
        id: row.id,
        question: row.question,
      }));
    },
    () => mockFaqItems,
  ),
);
