import { sql } from 'drizzle-orm';
import { businesses, commercials, users } from './drizzle/schema.js';
import { BusinessListing, CommercialPropertyListing, User } from './models/db.model.js';
export const EARTH_RADIUS_KM = 6371; // Erdradius in Kilometern
export const EARTH_RADIUS_MILES = 3959; // Erdradius in Meilen
export function convertStringToNullUndefined(value) {
  // Konvertiert den Wert zu Kleinbuchstaben für eine case-insensitive Überprüfung
  const lowerCaseValue = typeof value === 'boolean' ? value : value?.toLowerCase();

  if (lowerCaseValue === 'null') {
    return null;
  } else if (lowerCaseValue === 'undefined') {
    return undefined;
  }

  // Gibt den Originalwert zurück, wenn es sich nicht um 'null' oder 'undefined' handelt
  return value;
}

export const getDistanceQuery = (schema: typeof businesses | typeof commercials | typeof users, lat: number, lon: number, unit: 'km' | 'miles' = 'miles') => {
  const radius = unit === 'km' ? EARTH_RADIUS_KM : EARTH_RADIUS_MILES;

  return sql`
    ${radius} * 2 * ASIN(SQRT(
      POWER(SIN((${lat} - ${schema.latitude}) * PI() / 180 / 2), 2) +
      COS(${lat} * PI() / 180) * COS(${schema.latitude} * PI() / 180) *
      POWER(SIN((${lon} - ${schema.longitude}) * PI() / 180 / 2), 2)
    ))
  `;
};

type DrizzleUser = typeof users.$inferSelect;
type DrizzleBusinessListing = typeof businesses.$inferSelect;
type DrizzleCommercialPropertyListing = typeof commercials.$inferSelect;
export function convertBusinessToDrizzleBusiness(businessListing: Partial<BusinessListing>): DrizzleBusinessListing {
  return flattenObject(businessListing);
}
export function convertDrizzleBusinessToBusiness(drizzleBusinessListing: Partial<DrizzleBusinessListing>): BusinessListing {
  const o = {
    location_city: drizzleBusinessListing.city,
    location_state: drizzleBusinessListing.state,
    location_latitude: drizzleBusinessListing.latitude,
    location_longitude: drizzleBusinessListing.longitude,
    ...drizzleBusinessListing,
  };
  delete o.city;
  delete o.state;
  delete o.latitude;
  delete o.longitude;
  return unflattenObject(o);
}
export function convertCommercialToDrizzleCommercial(commercialPropertyListing: Partial<CommercialPropertyListing>): DrizzleCommercialPropertyListing {
  return flattenObject(commercialPropertyListing);
}
export function convertDrizzleCommercialToCommercial(drizzleCommercialPropertyListing: Partial<DrizzleCommercialPropertyListing>): CommercialPropertyListing {
  const o = {
    location_city: drizzleCommercialPropertyListing.city,
    location_state: drizzleCommercialPropertyListing.state,
    location_latitude: drizzleCommercialPropertyListing.latitude,
    location_longitude: drizzleCommercialPropertyListing.longitude,
    ...drizzleCommercialPropertyListing,
  };
  delete o.city;
  delete o.state;
  delete o.latitude;
  delete o.longitude;
  return unflattenObject(o);
}
export function convertUserToDrizzleUser(user: Partial<User>): DrizzleUser {
  return flattenObject(user);
}

export function convertDrizzleUserToUser(drizzleUser: Partial<DrizzleUser>): User {
  const o = {
    companyLocation_city: drizzleUser.city,
    companyLocation_state: drizzleUser.state,
    companyLocation_latitude: drizzleUser.latitude,
    companyLocation_longitude: drizzleUser.longitude,
    ...drizzleUser,
  };
  delete o.city;
  delete o.state;
  delete o.latitude;
  delete o.longitude;
  return unflattenObject(o);
}
function flattenObject(obj: any, res: any = {}): any {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];

      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        if (value instanceof Date) {
          res[key] = value;
        } else {
          flattenObject(value, res);
        }
      } else {
        res[key] = value;
      }
    }
  }
  return res;
}
function unflattenObject(obj: any, separator: string = '_'): any {
  const result: any = {};

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const keys = key.split(separator);
      keys.reduce((acc, curr, idx) => {
        if (idx === keys.length - 1) {
          acc[curr] = obj[key];
        } else {
          if (!acc[curr]) {
            acc[curr] = {};
          }
        }
        return acc[curr];
      }, result);
    }
  }

  return result;
}
