import { getActuateConfig } from '../config/runtime.js';
import { getSeoOverrides, applySeoOverrides, resolveSeoModuleSettings, } from './config-store.js';
import { resolveSeoEnvironment } from './robots.js';
/**
 * Detect a blanket `Disallow: /` in a custom robots.txt body — i.e. a rule that
 * blocks the entire site (path is exactly `/`, optionally trailing comment).
 */
export function robotsTxtBlocksEntireSite(robotsTxt) {
    if (!robotsTxt)
        return false;
    return /(^|\n)\s*disallow:\s*\/\s*(#.*)?$/im.test(robotsTxt);
}
const ACTIONS = [
    { label: 'Run SEO Audit', href: '/seo?tab=audit', action: 'run_seo_audit' },
    { label: 'View robots.txt', href: '/robots.txt' },
    { label: 'View sitemap.xml', href: '/sitemap.xml' },
];
function yesNo(value) {
    return value ? 'Yes' : 'No';
}
export function computeSiteIndexStatus(input) {
    const environment = input.environment ?? 'unknown';
    const isProduction = environment === 'production';
    const seo = input.seo ?? {};
    const robots = seo.robots ?? {};
    const siteUrl = (seo.siteUrl ?? '').trim();
    const hasSiteUrl = siteUrl.length > 0;
    const robotsRouteDisabled = robots.disabled === true || input.module.robotsEnabled === false;
    const customRobots = input.module.robotsTxt?.trim() ? input.module.robotsTxt : '';
    const robotsBlocksAll = customRobots ? robotsTxtBlocksEntireSite(customRobots) : false;
    const globalNoindex = robots.defaultNoIndex === true;
    const nonProdNoindex = robots.noIndexNonProduction === true;
    const sitemapEnabled = seo.sitemap?.disabled !== true && input.module.sitemapEnabled !== false;
    const checks = [
        {
            key: 'environment',
            label: 'Environment',
            value: environment === 'unknown' ? 'Unknown' : capitalize(environment),
            status: environment === 'unknown' ? 'unknown' : 'pass',
        },
        {
            key: 'siteUrl',
            label: 'Site URL configured',
            value: yesNo(hasSiteUrl),
            status: hasSiteUrl ? 'pass' : 'warning',
        },
        {
            key: 'robotsBlockAll',
            label: 'Robots.txt blocking all',
            value: yesNo(robotsRouteDisabled || robotsBlocksAll),
            status: robotsRouteDisabled || robotsBlocksAll ? (isProduction ? 'fail' : 'warning') : 'pass',
        },
        {
            key: 'globalNoindex',
            label: 'Global noindex',
            value: globalNoindex ? 'On' : 'Off',
            status: globalNoindex ? (isProduction ? 'fail' : 'warning') : 'pass',
        },
        {
            key: 'nonProdNoindex',
            label: 'Non-production noindex',
            value: nonProdNoindex ? 'On' : 'Off',
            // Off is a warning only in a non-production environment (it may be indexed).
            status: nonProdNoindex ? 'pass' : isProduction ? 'pass' : 'warning',
        },
        {
            key: 'sitemap',
            label: 'Sitemap enabled',
            value: yesNo(sitemapEnabled),
            status: sitemapEnabled ? 'pass' : 'warning',
        },
        {
            key: 'lastAudit',
            label: 'Last SEO audit',
            value: input.lastAuditAt ? formatAuditDate(input.lastAuditAt) : 'Never',
            status: input.lastAuditAt ? 'pass' : 'unknown',
        },
    ];
    const base = { environment, checks, actions: ACTIONS, lastAuditAt: input.lastAuditAt };
    if (!input.hasSeoConfig) {
        return {
            ...base,
            status: 'unknown',
            severity: 'neutral',
            label: 'Unknown',
            description: 'Run an SEO audit to verify crawl/index status.',
        };
    }
    if (isProduction && (robotsRouteDisabled || robotsBlocksAll || globalNoindex)) {
        return {
            ...base,
            status: 'blocked',
            severity: 'danger',
            label: 'Blocked',
            description: 'Search engines are currently blocked from indexing this production site.',
        };
    }
    if (!isProduction && nonProdNoindex) {
        return {
            ...base,
            status: 'protected',
            severity: 'warning',
            label: 'Protected',
            description: 'Non-production environment is noindexed. Production remains unaffected.',
        };
    }
    // Non-production without the guard, or otherwise blocked in a non-prod env.
    if (!isProduction && (robotsRouteDisabled || robotsBlocksAll || globalNoindex)) {
        return {
            ...base,
            status: 'blocked',
            severity: 'warning',
            label: 'Blocked',
            description: 'Indexing is disabled in this non-production environment.',
        };
    }
    if (!hasSiteUrl) {
        return {
            ...base,
            status: 'unknown',
            severity: 'warning',
            label: 'Needs attention',
            description: 'Site URL is not configured — canonical, sitemap, and Open Graph URLs may be invalid.',
        };
    }
    if (!isProduction && !nonProdNoindex) {
        return {
            ...base,
            status: 'partially_blocked',
            severity: 'warning',
            label: 'Partially blocked',
            description: 'This non-production environment can be indexed if publicly accessible. Enable non-production noindex to protect it.',
        };
    }
    if (!sitemapEnabled) {
        return {
            ...base,
            status: 'partially_blocked',
            severity: 'warning',
            label: 'Partially blocked',
            description: 'Production pages can be indexed, but the sitemap is disabled.',
        };
    }
    return {
        ...base,
        status: 'indexable',
        severity: 'success',
        label: 'Indexable',
        description: 'Production pages can be indexed unless individually noindexed.',
    };
}
/** Gather effective SEO config + module + environment + last audit, then compute. */
export async function getSiteIndexStatus(db) {
    const base = getActuateConfig() ?? null;
    const overrides = await getSeoOverrides(db);
    const effective = applySeoOverrides(base, overrides);
    const seo = effective?.seo ?? base?.seo ?? null;
    const seoModule = resolveSeoModuleSettings(overrides);
    const hasSeoConfig = Boolean(seo) || Boolean(overrides);
    let lastAuditAt = null;
    try {
        const d = db;
        if (d?.seoAuditRun?.findFirst) {
            const run = (await d.seoAuditRun.findFirst({
                where: { status: 'COMPLETED' },
                orderBy: { startedAt: 'desc' },
                select: { finishedAt: true, startedAt: true },
            }));
            const ts = run?.finishedAt ?? run?.startedAt ?? null;
            lastAuditAt = ts ? new Date(ts).toISOString() : null;
        }
    }
    catch {
        // Audit table may be unavailable (older schema / mock client) — leave null.
    }
    return computeSiteIndexStatus({
        environment: resolveSeoEnvironment(),
        seo,
        module: seoModule,
        hasSeoConfig,
        lastAuditAt,
    });
}
function capitalize(value) {
    return value.charAt(0).toUpperCase() + value.slice(1);
}
function formatAuditDate(iso) {
    const d = new Date(iso);
    if (Number.isNaN(d.getTime()))
        return 'Never';
    return d.toISOString().slice(0, 10);
}
//# sourceMappingURL=index-status.js.map