import { NextResponse } from "next/server";

export type ApiSuccess<T> = {
  code: 0;
  message: "ok";
  data: T;
};

export type ApiError = {
  code: string;
  message: string;
  data: null;
};

export type ApiEnvelope<T> = ApiSuccess<T> | ApiError;

const NO_STORE_HEADERS = {
  "Cache-Control": "no-store",
} as const;

export function ok<T>(
  data: T,
  init?: ResponseInit,
): NextResponse<ApiSuccess<T>> {
  return NextResponse.json(
    { code: 0, message: "ok", data },
    {
      status: 200,
      ...init,
      headers: {
        ...NO_STORE_HEADERS,
        ...init?.headers,
      },
    },
  );
}

export function fail(
  code: string,
  message: string,
  httpStatus: number,
): NextResponse<ApiError> {
  return NextResponse.json(
    { code, message, data: null },
    {
      status: httpStatus,
      headers: NO_STORE_HEADERS,
    },
  );
}

/** 查价接口响应头辅助：强制 no-store */
export function withNoStore(headers?: HeadersInit): HeadersInit {
  return {
    ...NO_STORE_HEADERS,
    ...headers,
  };
}
