import { cookies } from "next/headers";
import { fail, ok } from "@/lib/response";
import {
  EMBED_DEMO_COOKIE,
  verifyEmbedDemoToken,
} from "@/modules/embed-demo/auth";
import { isKnownCustomer } from "@/modules/auth/service-token-env";
import { isDbCustomerActive } from "@/modules/customer/customer-service";
import {
  defaultMarkupDto,
  serializeMarkupConfig,
} from "@/modules/pricing/markup-service";
import { hasCustomerProviderCredential } from "@/modules/customer/provider-credentials";
import { prisma } from "@/lib/prisma";

async function isEmbedCustomerAllowed(customerId: string): Promise<boolean> {
  if (isKnownCustomer(customerId)) {
    return true;
  }
  return isDbCustomerActive(customerId);
}

async function loadProviderFlags(customerId: string) {
  const [mothership, flock] = await Promise.all([
    hasCustomerProviderCredential(customerId, "mothership"),
    hasCustomerProviderCredential(customerId, "flock"),
  ]);
  return {
    mothership: { has_password: mothership },
    flock: { has_password: flock },
  };
}

/** GET /api/embed-demo/me — 当前演示会话与加价配置 */
export async function GET() {
  const cookieStore = await cookies();
  const raw = cookieStore.get(EMBED_DEMO_COOKIE)?.value;
  if (!raw) {
    return fail("UNAUTHORIZED", "未登录", 401);
  }

  let customerId: string;
  let loginType: string;
  try {
    const payload = await verifyEmbedDemoToken(raw);
    customerId = payload.sub;
    loginType = payload.loginType;
  } catch {
    return fail("UNAUTHORIZED", "演示会话无效或已过期", 401);
  }

  if (!(await isEmbedCustomerAllowed(customerId))) {
    return fail("FORBIDDEN", "客户已停用", 403);
  }

  const markupRow = await prisma.markupConfig.findFirst({
    where: { customerId, isDeleted: false },
  });
  const markup = markupRow
    ? serializeMarkupConfig(markupRow)
    : defaultMarkupDto(customerId);

  return ok({
    customer_id: customerId,
    login_type: loginType,
    markup,
    providers: await loadProviderFlags(customerId),
  });
}
