import {
  ok,
  type ReadonlyDB,
  type PaginationInput,
  buildPaginatedResult,
  DEFAULT_PAGE_SIZE,
} from "@tailor-platform/erp-kit/core";
import type { PartnerAddressAddressType } from "../generated/enums";
import type { DB } from "../generated/kysely-tailordb";

type OrderByField = "createdAt";

export interface ListPartnerAddressesByPartnerInput extends PaginationInput<OrderByField> {
  partnerId: string;
  addressType?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListPartnerAddressesByPartnerInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "asc";

  let query = db.selectFrom("PartnerAddress").selectAll().where("partnerId", "=", input.partnerId);

  if (input.addressType !== undefined) {
    query = query.where("addressType", "=", input.addressType as PartnerAddressAddressType);
  }

  const items = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  return ok(buildPaginatedResult(items, limit));
}
