import mongoose from 'mongoose';
import { ILocation, ILocationModel } from '../types';

const { Schema } = mongoose;

const LocationSchema = new Schema(
  {
    latitude: { type: Number, required: true },
    longitude: { type: Number, required: true },
    City: { type: String },
    address: { type: String },
    country: { type: String },
    state: { type: String },
    postalCode: { type: String },
    street: { type: String },
  },
  {
    timestamps: true,
  }
);

// Static method to reverse geocode coordinates and get full address details
LocationSchema.statics.reverseGeocode = async function (lat: number, lon: number) {
  try {
    // Dynamically import node-fetch
    const fetchModule = await import('node-fetch');
    const fetch = fetchModule.default;

    const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(lon)}&addressdetails=1`;

    const response = await fetch(url, {
      headers: {
        'User-Agent': 'LocationApp/1.0',
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = (await response.json()) as {
      display_name?: string;
      address?: {
        city?: string;
        town?: string;
        village?: string;
        municipality?: string;
        country?: string;
        state?: string;
        province?: string;
        region?: string;
        postcode?: string;
        house_number?: string;
        road?: string;
      };
    };

    // Extract address components
    const addressComponents = data.address;
    const displayName = data.display_name;

    if (addressComponents) {
      return {
        city:
          addressComponents.city ||
          addressComponents.town ||
          addressComponents.village ||
          addressComponents.municipality ||
          null,
        address: displayName || null,
        country: addressComponents.country || null,
        state:
          addressComponents.state ||
          addressComponents.province ||
          addressComponents.region ||
          null,
        postalCode: addressComponents.postcode || null,
        street:
          `${addressComponents.house_number || ''} ${addressComponents.road || ''}`.trim() ||
          null,
      };
    }

    return {
      city: null,
      address: null,
      country: null,
      state: null,
      postalCode: null,
      street: null,
    };
  } catch (error) {
    console.error('Error in reverse geocoding:', error);
    return {
      city: null,
      address: null,
      country: null,
      state: null,
      postalCode: null,
      street: null,
    };
  }
};

// Static method to create location with automatic address lookup
LocationSchema.statics.createWithGeocode = async function (
  latitude: number,
  longitude: number
): Promise<ILocation> {
  const geocodeResult = await (this as unknown as ILocationModel).reverseGeocode(
    latitude,
    longitude
  );

  const location = new this({
    latitude,
    longitude,
    City: geocodeResult.city,
    address: geocodeResult.address,
    country: geocodeResult.country,
    state: geocodeResult.state,
    postalCode: geocodeResult.postalCode,
    street: geocodeResult.street,
  });

  return await location.save();
};

const LocationModel = mongoose.model<ILocationModel>(
  'Location',
  LocationSchema
);
export default LocationModel;
