import { prisma } from '@/lib/db';
/** ContentStatus — mirrors the Prisma enum removed during Convex migration */
const ContentStatus = { DRAFT: 'DRAFT', PUBLISHED: 'PUBLISHED' } as const;
type ContentStatus = (typeof ContentStatus)[keyof typeof ContentStatus];
import { getSectionConfig } from './config';
import { validatePreviewToken } from './preview';

export interface FetchOptions {
  lang?: string;
  previewToken?: string | null;
  status?: ContentStatus;
  pagePath?: string;
}

const SECTION_DEFAULT_LANG = 'en';

async function resolveStatus(
  requested: ContentStatus | undefined,
  section: string,
  lang: string,
  previewToken?: string | null
) {
  if (requested === ContentStatus.DRAFT) {
    const previewOk = await validatePreviewToken(previewToken ?? null, section, lang);
    if (previewOk) return ContentStatus.DRAFT;
    return ContentStatus.PUBLISHED;
  }
  if (previewToken) {
    const previewOk = await validatePreviewToken(previewToken, section, lang);
    if (previewOk) return ContentStatus.DRAFT;
  }
  return ContentStatus.PUBLISHED;
}

export async function getContentSection(
  section: string,
  opts: FetchOptions = {}
) {
  const config = getSectionConfig(section);
  if (!config) return null;

  const lang = opts.lang ?? SECTION_DEFAULT_LANG;

  try {
    const status = await resolveStatus(opts.status, section, lang, opts.previewToken);
    const model = (prisma as any)[config.model];

    const record = await model.findFirst({
      where: { lang, status },
      orderBy: { updatedAt: 'desc' },
    });

    return record;
  } catch (error) {
    // Handle database connection errors gracefully during build or development
    // During Docker build, database is not available but NODE_ENV is production
    const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build';
    const isDev = process.env.NODE_ENV === 'development';
    const isDbConnectionError = (error as Error).message?.includes("Can't reach database");

    if (isDev || isBuildTime || isDbConnectionError) {
      console.warn(`[site-content] Database unavailable for section "${section}":`, (error as Error).message?.slice(0, 100));
      return null;
    }
    throw error;
  }
}

export async function getAnnouncementsForPage(
  opts: FetchOptions = {}
) {
  const lang = opts.lang ?? SECTION_DEFAULT_LANG;
  const pagePath = opts.pagePath;

  try {
    const status = await resolveStatus(opts.status, 'announcements', lang, opts.previewToken);
    const now = new Date();

    const records = await prisma.announcements.findMany({
      where: {
        lang,
        status,
        OR: pagePath ? [
          { targetPages: { isEmpty: true } },
          { targetPages: { has: pagePath } },
        ] : undefined,
        AND: [
          { OR: [{ startAt: null }, { startAt: { lte: now } }] },
          { OR: [{ endAt: null }, { endAt: { gte: now } }] },
        ],
      },
      orderBy: { updatedAt: 'desc' },
    });

    return records;
  } catch (error) {
    const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build';
    const isDev = process.env.NODE_ENV === 'development';
    const isDbConnectionError = (error as Error).message?.includes("Can't reach database");

    if (isDev || isBuildTime || isDbConnectionError) {
      console.warn(`[site-content] Database unavailable for announcements:`, (error as Error).message?.slice(0, 100));
      return [];
    }
    throw error;
  }
}

export async function getEvents(
  opts: FetchOptions = {}
) {
  const lang = opts.lang ?? SECTION_DEFAULT_LANG;

  try {
    const status = await resolveStatus(opts.status, 'events', lang, opts.previewToken);

    const records = await prisma.events.findMany({
      where: {
        lang,
        status,
        OR: [{ publishToSite: true }, { publishToSocial: true }],
      },
      orderBy: { startAt: 'asc' },
    });

    return records;
  } catch (error) {
    const isBuildTime = process.env.NEXT_PHASE === 'phase-production-build';
    const isDev = process.env.NODE_ENV === 'development';
    const isDbConnectionError = (error as Error).message?.includes("Can't reach database");

    if (isDev || isBuildTime || isDbConnectionError) {
      console.warn(`[site-content] Database unavailable for events:`, (error as Error).message?.slice(0, 100));
      return [];
    }
    throw error;
  }
}
