import { NextRequest, NextResponse } from "next/server";
import { GridColDef } from "@mui/x-data-grid-pro";
import { Database, db, getWorkerUtils } from "bridge-common";
import { getServiceTable } from "../config/config";

const entities = [
  "facebook",
  "whatsapp",
  "signal",
  "voice",
  "webhooks",
  "users",
] as const;

export type Entity = (typeof entities)[number];

export type SelectOption = {
  value: string;
  label: string;
};

export type FieldDescription = {
  name: string;
  label: string;
  kind?: "text" | "phone" | "select" | "multi";
  getOptions?: (formState: any) => Promise<SelectOption[]>;
  autogenerated?: "token";
  hidden?: boolean;
  type?: string;
  lines?: number;
  copyable?: boolean;
  refreshable?: boolean;
  defaultValue?: string;
  required?: boolean;
  disabled?: boolean;
  size?: number;
  helperText?: string;
};

export type ServiceConfig = {
  entity: Entity;
  table: keyof Database;
  displayName: string;
  createFields: FieldDescription[];
  updateFields: FieldDescription[];
  displayFields: FieldDescription[];
  listColumns: GridColDef[];
};

export type ServiceParams = {
  params: {
    service: string;
    token?: string;
  };
};

export class Service {
  async getBot({
    params: { service, token },
  }: ServiceParams): Promise<NextResponse> {
    const table = getServiceTable(service);
    const row = await db
      .selectFrom(table)
      .selectAll()
      .where("token", "=", token ?? "NEVER_MATCH")
      .executeTakeFirstOrThrow();

    return NextResponse.json(row);
  }

  async sendMessage(
    req: NextRequest,
    { params: { service, token } }: ServiceParams,
  ): Promise<NextResponse> {
    const message = await req.json();
    const worker = await getWorkerUtils();
    await worker.addJob(`${service}/send-${service}-message`, {
      token,
      message,
    });

    return NextResponse.json({ response: "ok" });
  }

  async handleWebhook(_req: NextRequest): Promise<NextResponse> {
    return NextResponse.error() as any;
  }
}
