import { FieldType, type Segment } from "@hamradio/packet";

import { DataType, type Payload, type QueryPayload } from "./frame.types";

export const decodeQueryPayload = (
  raw: string,
  withStructure: boolean = false
): {
  payload: Payload | null;
  segment?: Segment[];
} => {
  try {
    if (raw.length < 2) return { payload: null };

    // Skip data type identifier '?'
    const segments: Segment[] = withStructure ? [] : [];

    // Remaining payload
    const rest = raw.substring(1).trim();
    if (!rest) return { payload: null };

    // Query type is the first token (up to first space)
    const firstSpace = rest.indexOf(" ");
    let queryType = "";
    let target: string | undefined = undefined;

    if (firstSpace === -1) {
      queryType = rest;
    } else {
      queryType = rest.substring(0, firstSpace);
      target = rest.substring(firstSpace + 1).trim();
      if (target === "") target = undefined;
    }

    if (!queryType) return { payload: null };

    if (withStructure) {
      // Emit query type section
      segments.push({
        name: "query type",
        data: new TextEncoder().encode(queryType).buffer,
        isString: true,
        fields: [{ type: FieldType.STRING, name: "type", length: queryType.length }]
      });

      if (target) {
        segments.push({
          name: "query target",
          data: new TextEncoder().encode(target).buffer,
          isString: true,
          fields: [{ type: FieldType.STRING, name: "target", length: target.length }]
        });
      }
    }

    const payload: QueryPayload = {
      type: DataType.Query,
      queryType,
      ...(target ? { target } : {})
    };

    if (withStructure) return { payload, segment: segments };
    return { payload };
  } catch {
    return { payload: null };
  }
};

export default decodeQueryPayload;
