import { z } from "zod/v4";
import { eq } from "drizzle-orm";
import { fn } from "../utils/fn.js";
import { Identifier } from "../id.js";
import { Examples } from "../examples.js";
import { Database } from "../drizzle/index.js";
import { apiPersonalTokenTable } from "./api.sql.js";

export namespace Personal {
  export const Info = z
    .object({
      id: Identifier.schema("apiPersonal").meta({
        description: "The unique identifier of the personal access token",
        example: Examples.Token.id,
      }),
      created: z.string().meta({
        description: "The creation timestamp of the personal access token",
        example: Examples.Token.created,
      }),
      token: z.string().meta({
        description:
          "A personal access token used to access the Nestri API. This is used to do things on behalf of the user.",
        example: Examples.Token.token,
      }),
    })
    .meta({
      ref: "PersonalToken",
      description: "Represents a personal access token for API authentication",
      example: Examples.Token,
    });

  export type Info = z.infer<typeof Info>;

  export const fromToken = fn(Info.shape.token, async (token: string) =>
    Database.transaction(async (tx) => {
      return tx
        .select({
          id: apiPersonalTokenTable.id,
          teamID: apiPersonalTokenTable.teamID,
        })
        .from(apiPersonalTokenTable)
        .where(eq(apiPersonalTokenTable.token, token))
        .then((rows) => rows.at(0));
    }),
  );
}
