import { pgTable, serial, text, jsonb, timestamp } from "drizzle-orm/pg-core";

// This table stores postcode search results from the OS Places API
// for re-use and caching purposes. The data is stored in jsonb format, to
// allow for fast queries and flexibility with the API response structure.

export interface OSPlacesHeader {
  totalresults?: number;
  offset?: number;
  maxresults?: number;
  [k: string]: any;
}

export interface OSPlacesItem {
  DPA?: Record<string, any>;
  LPI?: Record<string, any>;
}

export interface OSPlacesResponse {
  header?: OSPlacesHeader;
  results?: OSPlacesItem[];
}

export const postcodeSearch = pgTable("postcode_search", {
  id: serial("id").primaryKey(),

  // Normalized postcode (uppercase, no spaces)
  postcode: text("postcode").notNull().unique(),

  // Full OS Places API response
  resultData: jsonb("result_data").$type<OSPlacesResponse>().notNull(),

  // Timestamp for when the entry was first created
  createdAt: timestamp("created_at").defaultNow().notNull(),
  lastUpdatedAt: timestamp("last_updated_at").defaultNow().notNull(),
});
