import {
  pgTable,
  serial,
  text,
  jsonb,
  timestamp,
  bigint,
  uniqueIndex,
} 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 EpcApiResponse {
  header?: OSPlacesHeader;
  rows?: Record<string, any>;
}

export const epcStore = pgTable(
  "epc_store",
  {
    id: serial("id").primaryKey(),
    uprn: bigint("uprn", { mode: "bigint" }),

    // Timestamp for when the EPC API entry was first stored
    epcApiCreatedAt: timestamp("epc_api_created_at"),

    // EPC API response for the UPRN
    epcApi: jsonb("epc_api").$type<EpcApiResponse>(),

    // Timestamp for when the EPC page was stored
    epcPageCreatedAt: timestamp("epc_page_created_at"),

    // HTML content of the EPC page
    epcPage: text("epc_page"),

    // RRN of the EPC page
    epcPageRrn: text("epc_page_rrn"),
  },
  (table) => [uniqueIndex("uq_epc_store_uprn").on(table.uprn)]
);
