import "server-only";

import { readdir, stat } from "node:fs/promises";
import path from "node:path";
import { cache } from "react";
import { query } from "@/lib/db";
import { getMediaPublicUrl, normalizeMediaFolder, resolveUploadsAbsolutePath } from "@/lib/media-storage";
import { getPlainTextPreview } from "@/lib/rich-text";

export type AdminSelectOption = {
  id: string;
  label: string;
  value: string;
};

export type AdminCategoryItem = {
  description: string;
  id: string;
  imageUrl: string;
  isActive: boolean;
  metaDescription: string;
  metaTitle: string;
  name: string;
  slug: string;
  sortOrder: number;
};

export type AdminRegionItem = {
  description: string;
  id: string;
  imageUrl: string;
  isActive: boolean;
  metaDescription: string;
  metaTitle: string;
  name: string;
  slug: string;
  sortOrder: number;
};

export type AdminPropertyListItem = {
  dealType: string;
  id: string;
  image: string;
  location: string;
  price: number;
  status: string;
  title: string;
  type: string;
};

export type AdminPropertyFormData = {
  address: string;
  areaTotal: string;
  bathroomsCount: string;
  bedroomsCount: string;
  city: string;
  coverImageUrl: string;
  customFeatures: AdminPropertyFeatureItem[];
  dealTypeId: string;
  description: string;
  district: string;
  floorNumber: string;
  floorsTotal: string;
  id?: string;
  isFeatured: boolean;
  isLuxury: boolean;
  isNewBuild: boolean;
  latitude: string;
  longitude: string;
  price: string;
  propertyTypeId: string;
  refNumber: string;
  region: string;
  seoDescription: string;
  seoTitle: string;
  slug: string;
  statusId: string;
  title: string;
  yearBuilt: string;
};

export type AdminPropertyFeatureItem = {
  iconName: string;
  label: string;
  sortOrder: string;
  value: string;
};

export type AdminBlogItem = {
  author: string;
  category: string;
  content: string;
  excerpt: string;
  id: string;
  image: string;
  published: boolean;
  publishedAt: string;
  slug: string;
  tags: string[];
  title: string;
};

export type AdminFaqItem = {
  answer: string;
  category: string;
  id: string;
  pageId: string;
  question: string;
  sortOrder: number;
};

export type AdminPageItem = {
  content: string;
  excerpt: string;
  id: string;
  slug: string;
  status: "published" | "draft";
  title: string;
  updatedAt: string;
};

export type AdminInquiryItem = {
  createdAt: string;
  email: string;
  id: string;
  message: string;
  name: string;
  phone: string;
  propertyId?: string;
  propertyTitle?: string;
  status: string;
  type: "property" | "general" | "evaluation";
};

export type AdminDashboardData = {
  activeProperties: number;
  newInquiries: number;
  recentInquiries: AdminInquiryItem[];
  totalBlogPosts: number;
  totalInquiries: number;
  totalPageViews: number;
  totalProperties: number;
};

export type AdminCustomFieldItem = {
  code: string;
  defaultValue: string;
  fieldType: string;
  helpText: string;
  id: string;
  isRequired: boolean;
  isVisibleInDetail: boolean;
  isVisibleInListing: boolean;
  label: string;
  options: string[];
  propertyTypeId: string;
  propertyTypeLabel: string;
  section: string;
  showInFilter: boolean;
  sortOrder: number;
};

export type AdminRoleItem = {
  code: string;
  description: string;
  isActive: boolean;
  menuKeys: string[];
  name: string;
};

export type AdminUserItem = {
  email: string;
  fullName: string;
  id: string;
  isActive: boolean;
  lastLoginAt: string;
  menuKeys: string[];
  roleCode: string;
};

export type AdminGeneralSettings = {
  contactAddress: string;
  contactEmail: string;
  contactPhone: string;
  siteName: string;
};

export type AdminPublicUserItem = {
  createdAt: string;
  email: string;
  favoritesCount: number;
  fullName: string;
  id: string;
  inquiriesCount: number;
  isActive: boolean;
  lastLoginAt: string;
  phone: string;
};

export type AdminSettingsData = {
  general: AdminGeneralSettings;
  menus: Array<{
    key: string;
    label: string;
    path: string;
  }>;
  roles: AdminRoleItem[];
  users: AdminUserItem[];
};

export type AdminMediaFolderItem = {
  fileCount: number;
  folderCount: number;
  modifiedAt: string;
  name: string;
  path: string;
  url: string;
};

export type AdminMediaFileItem = {
  modifiedAt: string;
  name: string;
  path: string;
  sizeBytes: number;
  sizeLabel: string;
  url: string;
};

export type AdminMediaLibraryData = {
  breadcrumbs: Array<{
    label: string;
    path: string;
  }>;
  currentFolder: string;
  files: AdminMediaFileItem[];
  folders: AdminMediaFolderItem[];
};

function dateOnly(value: string | null) {
  return value ? new Date(value).toISOString().slice(0, 10) : "";
}

function dateTimeLabel(value: Date) {
  return value.toISOString().slice(0, 16).replace("T", " ");
}

function formatBytes(value: number) {
  if (value < 1024) {
    return `${value} B`;
  }

  if (value < 1024 * 1024) {
    return `${(value / 1024).toFixed(1)} KB`;
  }

  return `${(value / (1024 * 1024)).toFixed(1)} MB`;
}

function mapInquiryType(code: string): "property" | "general" | "evaluation" {
  if (code === "valuation") {
    return "evaluation";
  }

  if (code === "property") {
    return "property";
  }

  return "general";
}

export const getAdminPropertyLookups = cache(async () => {
  const [propertyTypes, dealTypes, statuses, regions] = await Promise.all([
    query<{ id: string; name: string }>(
      `SELECT id::text, name FROM property_types WHERE is_active = true ORDER BY sort_order ASC, name ASC`,
    ),
    query<{ id: string; name: string }>(
      `SELECT id::text, name FROM deal_types WHERE is_active = true ORDER BY name ASC`,
    ),
    query<{ id: string; name: string }>(
      `SELECT id::text, name FROM property_statuses ORDER BY sort_order ASC, name ASC`,
    ),
    query<{ id: string; name: string }>(`
      SELECT l.id::text, l.name
      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 {
    dealTypes: dealTypes.rows.map((item) => ({
      id: item.id,
      label: item.name,
      value: item.id,
    })),
    propertyTypes: propertyTypes.rows.map((item) => ({
      id: item.id,
      label: item.name,
      value: item.id,
    })),
    regions: regions.rows.map((item) => ({
      id: item.id,
      label: item.name,
      value: item.name,
    })),
    statuses: statuses.rows.map((item) => ({
      id: item.id,
      label: item.name,
      value: item.id,
    })),
  };
});

export const getAdminCategories = cache(async (): Promise<AdminCategoryItem[]> => {
  const result = await query<{
    description: string | null;
    id: string;
    image_url: string | null;
    is_active: boolean;
    name: string;
    slug: string;
    sort_order: number;
  }>(`
    SELECT
      id::text,
      name,
      slug,
      description,
      image_url,
      sort_order,
      is_active
    FROM property_types
    ORDER BY sort_order ASC, name ASC
  `);

  return result.rows.map((row) => ({
    description: row.description || "",
    id: row.id,
    imageUrl: row.image_url || "",
    isActive: row.is_active,
    metaDescription: getPlainTextPreview(row.description || row.name, 160),
    metaTitle: row.name,
    name: row.name,
    slug: row.slug,
    sortOrder: row.sort_order,
  }));
});

export const getAdminRegions = cache(async (): Promise<AdminRegionItem[]> => {
  const result = await query<{
    description: string | null;
    id: string;
    image_url: string | null;
    is_active: boolean;
    name: string;
    slug: string;
    sort_order: number;
  }>(`
    SELECT
      l.id::text,
      l.name,
      l.slug,
      l.description,
      l.image_url,
      l.sort_order,
      l.is_active
    FROM locations l
    JOIN location_types lt ON lt.id = l.location_type_id
    WHERE lt.code = 'region'
    ORDER BY l.sort_order ASC, l.name ASC
  `);

  return result.rows.map((row) => ({
    description: row.description || "",
    id: row.id,
    imageUrl: row.image_url || "",
    isActive: row.is_active,
    metaDescription: getPlainTextPreview(row.description || row.name, 160),
    metaTitle: row.name,
    name: row.name,
    slug: row.slug,
    sortOrder: row.sort_order,
  }));
});

export const getAdminProperties = cache(async (): Promise<AdminPropertyListItem[]> => {
  const result = await query<{
    city_name: string | null;
    cover_image_url: string | null;
    deal_type_name: string;
    price: number | null;
    ref_number: string;
    region_name: string | null;
    status_code: string;
    title: string;
    type_name: string;
  }>(`
    SELECT
      p.ref_number,
      p.title,
      pt.name AS type_name,
      dt.name AS deal_type_name,
      p.price,
      ps.code AS status_code,
      city.name AS city_name,
      region.name AS region_name,
      (
        SELECT pm.file_url
        FROM property_media pm
        WHERE pm.property_id = p.id
        ORDER BY pm.is_cover DESC, pm.sort_order ASC, pm.created_at ASC
        LIMIT 1
      ) AS cover_image_url
    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 locations loc ON loc.id = p.location_id
    LEFT JOIN locations city ON city.id = CASE
      WHEN EXISTS (
        SELECT 1
        FROM location_types lt
        WHERE lt.id = loc.location_type_id
          AND lt.code = 'city'
      ) THEN loc.id
      ELSE loc.parent_id
    END
    LEFT JOIN locations region ON region.id = CASE
      WHEN city.id IS NOT NULL THEN city.parent_id
      ELSE loc.parent_id
    END
    WHERE p.deleted_at IS NULL
    ORDER BY COALESCE(p.published_at, p.created_at) DESC, p.ref_number DESC
  `);

  return result.rows.map((row) => ({
    dealType: row.deal_type_name,
    id: row.ref_number,
    image:
      row.cover_image_url ||
      "https://images.unsplash.com/photo-1502672260266-1c1ef2d93688?w=600",
    location: [row.city_name, row.region_name].filter(Boolean).join(", "),
    price: Number(row.price || 0),
    status: row.status_code,
    title: row.title,
    type: row.type_name,
  }));
});

export const getAdminPropertyFormData = cache(
  async (id?: string): Promise<AdminPropertyFormData | null> => {
    if (!id) {
      return null;
    }

    const result = await query<{
      address_text: string | null;
      area_total: number | null;
      bathrooms_count: number | null;
      bedrooms_count: number | null;
      city_name: string | null;
      cover_image_url: string | null;
      deal_type_id: string;
      description: string;
      district_name: string | null;
      floor_number: number | null;
      floors_total: number | null;
      id: string;
      is_featured: boolean;
      is_luxury: boolean;
      is_new_build: boolean;
      latitude: number | null;
      longitude: number | null;
      price: number | null;
      property_type_id: string;
      ref_number: string;
      region_name: string | null;
      seo_description: string | null;
      seo_title: string | null;
      slug: string;
      status_id: string;
      title: string;
      year_built: number | null;
    }>(`
      SELECT
        p.id::text,
        p.ref_number,
        p.slug,
        p.title,
        p.description,
        p.property_type_id::text,
        p.deal_type_id::text,
        p.status_id::text,
        p.price,
        p.area_total,
        p.bedrooms_count,
        p.bathrooms_count,
        p.floor_number,
        p.floors_total,
        p.year_built,
        p.address_text,
        p.latitude,
        p.longitude,
        p.is_featured,
        p.is_new_build,
        p.is_luxury,
        seo.title_tag AS seo_title,
        seo.meta_description AS seo_description,
        (
          SELECT pm.file_url
          FROM property_media pm
          WHERE pm.property_id = p.id
          ORDER BY pm.is_cover DESC, pm.sort_order ASC, pm.created_at ASC
          LIMIT 1
        ) AS cover_image_url,
        region.name AS region_name,
        city.name AS city_name,
        district.name AS district_name
      FROM properties p
      LEFT JOIN seo_metadata seo
        ON seo.entity_type = 'property'
        AND seo.entity_id = p.id
      LEFT JOIN locations loc ON loc.id = p.location_id
      LEFT JOIN locations city ON city.id = CASE
        WHEN EXISTS (
          SELECT 1
          FROM location_types lt
          WHERE lt.id = loc.location_type_id
            AND lt.code = 'city'
        ) THEN loc.id
        WHEN EXISTS (
          SELECT 1
          FROM location_types lt
          WHERE lt.id = loc.location_type_id
            AND lt.code IN ('district', 'subdistrict')
        ) THEN loc.parent_id
        ELSE NULL
      END
      LEFT JOIN locations region ON region.id = COALESCE(city.parent_id, loc.parent_id)
      LEFT JOIN locations district ON district.id = CASE
        WHEN EXISTS (
          SELECT 1
          FROM location_types lt
          WHERE lt.id = loc.location_type_id
            AND lt.code IN ('district', 'subdistrict')
        ) THEN loc.id
        ELSE NULL
      END
      WHERE p.ref_number = $1
        AND p.deleted_at IS NULL
      LIMIT 1
    `, [id]);

    const row = result.rows[0];

    if (!row) {
      return null;
    }

    const featureResult = await query<{
      icon_name: string;
      label: string;
      sort_order: number;
      value_text: string;
    }>(
      `
        SELECT
          icon_name,
          label,
          value_text,
          sort_order
        FROM property_feature_items
        WHERE property_id = $1::uuid
        ORDER BY sort_order ASC, created_at ASC
      `,
      [row.id],
    );

    return {
      address: row.address_text || "",
      areaTotal: row.area_total?.toString() || "",
      bathroomsCount: row.bathrooms_count?.toString() || "",
      bedroomsCount: row.bedrooms_count?.toString() || "",
      city: row.city_name || "",
      coverImageUrl: row.cover_image_url || "",
      customFeatures: featureResult.rows.map((feature) => ({
        iconName: feature.icon_name || "circle",
        label: feature.label,
        sortOrder: String(feature.sort_order || 0),
        value: feature.value_text,
      })),
      dealTypeId: row.deal_type_id,
      description: row.description,
      district: row.district_name || "",
      floorNumber: row.floor_number?.toString() || "",
      floorsTotal: row.floors_total?.toString() || "",
      id: row.id,
      isFeatured: row.is_featured,
      isLuxury: row.is_luxury,
      isNewBuild: row.is_new_build,
      latitude: row.latitude?.toString() || "",
      longitude: row.longitude?.toString() || "",
      price: row.price?.toString() || "",
      propertyTypeId: row.property_type_id,
      refNumber: row.ref_number,
      region: row.region_name || "",
      seoDescription: row.seo_description || "",
      seoTitle: row.seo_title || "",
      slug: row.slug,
      statusId: row.status_id,
      title: row.title,
      yearBuilt: row.year_built?.toString() || "",
    };
  },
);

export const getAdminBlogPosts = cache(async (): Promise<AdminBlogItem[]> => {
  const result = await query<{
    author_name: string | null;
    categories: string[] | null;
    content: string;
    excerpt: string | null;
    featured_image_url: string | null;
    id: string;
    is_published: boolean;
    published_at: string | null;
    slug: string;
    tags: string[] | null;
    title: string;
  }>(`
    SELECT
      bp.id::text,
      bp.title,
      bp.slug,
      bp.excerpt,
      bp.content,
      bp.author_name,
      bp.featured_image_url,
      bp.is_published,
      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
    GROUP BY bp.id
    ORDER BY COALESCE(bp.published_at, bp.created_at) DESC
  `);

  return result.rows.map((row) => ({
    author: row.author_name || "Редакционен екип",
    category: row.categories?.[0] || "Общи",
    content: row.content,
    excerpt: row.excerpt || "",
    id: row.id,
    image:
      row.featured_image_url ||
      "https://images.unsplash.com/photo-1555993539-1732b0258235?w=800",
    published: row.is_published,
    publishedAt: dateOnly(row.published_at),
    slug: row.slug,
    tags: row.tags || [],
    title: row.title,
  }));
});

export const getAdminFaqs = cache(async (): Promise<AdminFaqItem[]> => {
  const result = await query<{
    answer: string;
    id: string;
    page_id: string;
    page_title: string;
    question: string;
    sort_order: number;
  }>(`
    SELECT
      f.id::text,
      f.question,
      f.answer,
      f.sort_order,
      p.id::text AS page_id,
      p.title AS page_title
    FROM faqs f
    JOIN pages p ON p.id = f.page_id
    WHERE p.deleted_at IS NULL
    ORDER BY p.title ASC, f.sort_order ASC, f.created_at ASC
  `);

  return result.rows.map((row) => ({
    answer: row.answer,
    category: row.page_title,
    id: row.id,
    pageId: row.page_id,
    question: row.question,
    sortOrder: row.sort_order,
  }));
});

export const getAdminPages = cache(async (): Promise<AdminPageItem[]> => {
  const result = await query<{
    content: string;
    excerpt: string | null;
    id: string;
    is_published: boolean;
    slug: string;
    title: string;
    updated_at: string;
  }>(`
    SELECT
      p.id::text,
      p.title,
      p.slug,
      p.content,
      p.excerpt,
      p.is_published,
      p.updated_at
    FROM pages p
    WHERE p.deleted_at IS NULL
    ORDER BY p.updated_at DESC
  `);

  return result.rows.map((row) => ({
    content: row.content,
    excerpt: row.excerpt || "",
    id: row.id,
    slug: row.slug,
    status: row.is_published ? "published" : "draft",
    title: row.title,
    updatedAt: dateOnly(row.updated_at),
  }));
});

export const getAdminInquiries = cache(async (): Promise<AdminInquiryItem[]> => {
  const result = await query<{
    created_at: string;
    email: string;
    full_name: string;
    id: string;
    inquiry_type_code: string;
    message: string | null;
    phone: string | null;
    property_ref_number: string | null;
    property_title: string | null;
    status_code: string;
  }>(`
    SELECT
      i.id::text,
      i.full_name,
      i.email,
      i.phone,
      i.message,
      i.created_at,
      it.code AS inquiry_type_code,
      ist.code AS status_code,
      p.ref_number AS property_ref_number,
      p.title AS property_title
    FROM inquiries i
    JOIN inquiry_types it ON it.id = i.inquiry_type_id
    JOIN inquiry_statuses ist ON ist.id = i.status_id
    LEFT JOIN properties p ON p.id = i.property_id
    WHERE i.deleted_at IS NULL
    ORDER BY i.created_at DESC
  `);

  return result.rows.map((row) => ({
    createdAt: dateOnly(row.created_at),
    email: row.email,
    id: row.id,
    message: row.message || "",
    name: row.full_name,
    phone: row.phone || "",
    propertyId: row.property_ref_number || undefined,
    propertyTitle: row.property_title || undefined,
    status: row.status_code,
    type: mapInquiryType(row.inquiry_type_code),
  }));
});

export const getAdminDashboardData = cache(async (): Promise<AdminDashboardData> => {
  const [counts, recentInquiries] = await Promise.all([
    query<{
      active_properties: string;
      new_inquiries: string;
      total_blog_posts: string;
      total_inquiries: string;
      total_properties: string;
    }>(`
      SELECT
        (SELECT count(*)::text FROM properties WHERE deleted_at IS NULL) AS total_properties,
        (SELECT count(*)::text
         FROM properties p
         JOIN property_statuses ps ON ps.id = p.status_id
         WHERE p.deleted_at IS NULL
           AND ps.code = 'active') AS active_properties,
        (SELECT count(*)::text FROM inquiries WHERE deleted_at IS NULL) AS total_inquiries,
        (SELECT count(*)::text
         FROM inquiries i
         JOIN inquiry_statuses ist ON ist.id = i.status_id
         WHERE i.deleted_at IS NULL
           AND ist.code = 'new') AS new_inquiries,
        (SELECT count(*)::text FROM blog_posts WHERE deleted_at IS NULL) AS total_blog_posts
    `),
    getAdminInquiries(),
  ]);

  const row = counts.rows[0];

  return {
    activeProperties: Number(row?.active_properties || 0),
    newInquiries: Number(row?.new_inquiries || 0),
    recentInquiries: recentInquiries.slice(0, 5),
    totalBlogPosts: Number(row?.total_blog_posts || 0),
    totalInquiries: Number(row?.total_inquiries || 0),
    totalPageViews: 0,
    totalProperties: Number(row?.total_properties || 0),
  };
});

export const getAdminCustomFields = cache(async (): Promise<AdminCustomFieldItem[]> => {
  const result = await query<{
    code: string;
    default_value: string | null;
    field_type: string;
    group_name: string | null;
    help_text: string | null;
    id: string;
    is_filterable: boolean;
    is_required: boolean;
    is_visible_in_detail: boolean;
    is_visible_in_listing: boolean;
    label: string;
    options: string[] | null;
    property_type_id: string;
    property_type_name: string;
    sort_order: number;
  }>(`
    SELECT
      cfd.id::text,
      cfd.code,
      cfd.label,
      cfd.field_type,
      cfd.help_text,
      cfd.is_required,
      cfd.is_filterable,
      cfd.is_visible_in_listing,
      cfd.is_visible_in_detail,
      cfd.default_value,
      cfd.sort_order,
      cfd.property_type_id::text,
      pt.name AS property_type_name,
      cfg.name AS group_name,
      array_remove(array_agg(cfo.value_label ORDER BY cfo.sort_order), NULL) AS options
    FROM custom_field_definitions cfd
    JOIN property_types pt ON pt.id = cfd.property_type_id
    LEFT JOIN custom_field_groups cfg ON cfg.id = cfd.group_id
    LEFT JOIN custom_field_options cfo
      ON cfo.field_definition_id = cfd.id
      AND cfo.is_active = true
    WHERE cfd.is_active = true
    GROUP BY cfd.id, pt.name, cfg.name, cfg.sort_order
    ORDER BY pt.name ASC, cfg.sort_order ASC NULLS LAST, cfd.sort_order ASC, cfd.label ASC
  `);

  return result.rows.map((row) => ({
    code: row.code,
    defaultValue: row.default_value || "",
    fieldType: row.field_type,
    helpText: row.help_text || "",
    id: row.id,
    isRequired: row.is_required,
    isVisibleInDetail: row.is_visible_in_detail,
    isVisibleInListing: row.is_visible_in_listing,
    label: row.label,
    options: row.options || [],
    propertyTypeId: row.property_type_id,
    propertyTypeLabel: row.property_type_name,
    section: row.group_name || "Без секция",
    showInFilter: row.is_filterable,
    sortOrder: row.sort_order,
  }));
});

export const getAdminSettingsData = cache(async (): Promise<AdminSettingsData> => {
  const [menusResult, rolesResult, usersResult, settingsResult] = await Promise.all([
    query<{
      key: string;
      label: string;
      path: string;
    }>(`
      SELECT key, label, path
      FROM admin_menu_items
      WHERE is_active = true
      ORDER BY sort_order ASC, key ASC
    `),
    query<{
      code: string;
      description: string | null;
      is_active: boolean;
      menu_keys: string[] | null;
      name: string;
    }>(`
      SELECT
        ar.code,
        ar.name,
        ar.description,
        ar.is_active,
        array_remove(array_agg(ami.key ORDER BY ami.sort_order) FILTER (WHERE armp.can_access = true), NULL) AS menu_keys
      FROM admin_roles ar
      LEFT JOIN admin_role_menu_permissions armp ON armp.role_code = ar.code
      LEFT JOIN admin_menu_items ami ON ami.key = armp.menu_key
      GROUP BY ar.code
      ORDER BY ar.code ASC
    `),
    query<{
      email: string;
      full_name: string;
      id: string;
      is_active: boolean;
      last_login_at: string | null;
      menu_keys: string[] | null;
      role_code: string;
    }>(`
      SELECT
        au.id::text,
        au.full_name,
        au.email,
        au.role_code,
        au.is_active,
        au.last_login_at,
        array_remove(array_agg(aump.menu_key ORDER BY ami.sort_order) FILTER (WHERE aump.can_access = true), NULL) AS menu_keys
      FROM admin_users au
      LEFT JOIN admin_user_menu_permissions aump ON aump.user_id = au.id
      LEFT JOIN admin_menu_items ami ON ami.key = aump.menu_key
      WHERE au.deleted_at IS NULL
      GROUP BY au.id
      ORDER BY au.created_at ASC, au.email ASC
    `),
    query<{
      key: string;
      value: string;
    }>(`
      SELECT key, value
      FROM site_settings
      WHERE key IN ('site_name', 'contact_email', 'contact_phone', 'contact_address')
    `),
  ]);

  const settings = Object.fromEntries(
    settingsResult.rows.map((row) => [row.key, row.value]),
  );

  return {
    general: {
      contactAddress: settings.contact_address || "",
      contactEmail: settings.contact_email || "",
      contactPhone: settings.contact_phone || "",
      siteName: settings.site_name || "",
    },
    menus: menusResult.rows.map((row) => ({
      key: row.key,
      label: row.label,
      path: row.path,
    })),
    roles: rolesResult.rows.map((row) => ({
      code: row.code,
      description: row.description || "",
      isActive: row.is_active,
      menuKeys: row.menu_keys || [],
      name: row.name,
    })),
    users: usersResult.rows.map((row) => ({
      email: row.email,
      fullName: row.full_name,
      id: row.id,
      isActive: row.is_active,
      lastLoginAt: dateOnly(row.last_login_at),
      menuKeys: row.menu_keys || [],
      roleCode: row.role_code,
    })),
  };
});

export const getAdminPublicUsers = cache(async (): Promise<AdminPublicUserItem[]> => {
  const result = await query<{
    created_at: string;
    email: string;
    favorites_count: string;
    full_name: string;
    id: string;
    inquiries_count: string;
    is_active: boolean;
    last_login_at: string | null;
    phone: string | null;
  }>(`
    SELECT
      pu.id::text,
      pu.full_name,
      pu.email,
      pu.phone,
      pu.is_active,
      pu.created_at,
      pu.last_login_at,
      COUNT(DISTINCT puf.property_id)::text AS favorites_count,
      COUNT(DISTINCT i.id)::text AS inquiries_count
    FROM public_users pu
    LEFT JOIN public_user_favorites puf ON puf.user_id = pu.id
    LEFT JOIN inquiries i ON i.public_user_id = pu.id AND i.deleted_at IS NULL
    WHERE pu.deleted_at IS NULL
    GROUP BY pu.id
    ORDER BY pu.created_at DESC, pu.email ASC
  `);

  return result.rows.map((row) => ({
    createdAt: dateOnly(row.created_at),
    email: row.email,
    favoritesCount: Number(row.favorites_count || 0),
    fullName: row.full_name,
    id: row.id,
    inquiriesCount: Number(row.inquiries_count || 0),
    isActive: row.is_active,
    lastLoginAt: dateOnly(row.last_login_at),
    phone: row.phone || "",
  }));
});

export const getAdminMediaLibrary = cache(
  async (folder = ""): Promise<AdminMediaLibraryData> => {
    const currentFolder = normalizeMediaFolder(folder);
    const absoluteFolder = await resolveUploadsAbsolutePath(currentFolder);
    const entries = await readdir(absoluteFolder, { withFileTypes: true });

    const folders: AdminMediaFolderItem[] = [];
    const files: AdminMediaFileItem[] = [];

    for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
      const entryPath = currentFolder ? `${currentFolder}/${entry.name}` : entry.name;
      const absoluteEntryPath = path.join(absoluteFolder, entry.name);
      const entryStat = await stat(absoluteEntryPath);

      if (entry.isDirectory()) {
        const nestedEntries = await readdir(absoluteEntryPath, { withFileTypes: true });
        folders.push({
          fileCount: nestedEntries.filter((item) => item.isFile()).length,
          folderCount: nestedEntries.filter((item) => item.isDirectory()).length,
          modifiedAt: dateTimeLabel(entryStat.mtime),
          name: entry.name,
          path: entryPath,
          url: `/admin/media?folder=${encodeURIComponent(entryPath)}`,
        });
        continue;
      }

      files.push({
        modifiedAt: dateTimeLabel(entryStat.mtime),
        name: entry.name,
        path: entryPath,
        sizeBytes: entryStat.size,
        sizeLabel: formatBytes(entryStat.size),
        url: getMediaPublicUrl(entryPath),
      });
    }

    const breadcrumbs = [
      { label: "uploads", path: "" },
      ...currentFolder
        .split("/")
        .filter(Boolean)
        .map((segment, index, all) => ({
          label: segment,
          path: all.slice(0, index + 1).join("/"),
        })),
    ];

    return {
      breadcrumbs,
      currentFolder,
      files,
      folders,
    };
  },
);
