import type { UserLocation } from "../generated/prisma/client";
import { prisma } from "../prisma/db";

const xprisma = prisma.$extends({
  model: {
    userLocation: {
      updateLocation: async (id: number, point: { lat: number; lng: number }) => {
        return prisma.$queryRaw`
          UPDATE UserLocation SET
          coords=ST_GeomFromText(${`POINT(${point.lng} ${point.lat})`}, 4326)
          WHERE id = ${id};
        `;
      },
      createCustom: async (logto_uid: string, name: string, point: { lat: number; lng: number }, kaiqiu_uid?: string) => {
        return prisma.$executeRaw`
          INSERT INTO UserLocation(logto_uid, kaiqiu_uid, name, coords) 
          VALUES (
            ${logto_uid},
            ${kaiqiu_uid},
            ${name}, 
            ST_GeomFromText(${`POINT(${point.lng} ${point.lat})`}, 4326)
          )
        `;
      },
      findAll: async (): Promise<(UserLocation & {
        lat: number;
        lng: number;
      })[]> => {
        return prisma.$queryRaw`
          SELECT id, kaiqiu_uid, logto_uid, name, ST_X(coords) as lng, ST_Y(coords) as lat
          FROM UserLocation;
        `;
      },
      findManyWihtLocation: async (logto_uid: string): Promise<(UserLocation & {
        lat: number;
        lng: number;
      })[]> => {
        return prisma.$queryRaw`
          SELECT id, kaiqiu_uid, logto_uid, name, ST_X(coords) as lng, ST_Y(coords) as lat
          FROM UserLocation
          where logto_uid = ${`${logto_uid}`};
        `;
      },
      findNearby(point: { lat: number; lng: number }, distance: number): Promise<(UserLocation & {
        lat: number;
        lng: number;
      })[]> {
        return prisma.$queryRaw`
          SELECT id, kaiqiu_uid, logto_uid, name, ST_X(coords) as lng, ST_Y(coords) as lat
          FROM UserLocation
          WHERE ST_Distance_Sphere(coords, ST_GeomFromText(${`POINT(${point.lng} ${point.lat})`}, 4326)) <= ${distance}
        `;
      }
    }
  }
});

export default xprisma;