// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { DAY, WEEK } from "./constants.ts";

const DAYS_PER_WEEK = 7;

const Day = {
  Sun: 0,
  Mon: 1,
  Tue: 2,
  Wed: 3,
  Thu: 4,
  Fri: 5,
  Sat: 6,
} as const;

/**
 * Returns the ISO week number of the provided date (1-53).
 *
 * @param date Date to get the week number of.
 * @returns The week number of the provided date.
 *
 * @example Basic usage
 * ```ts
 * import { weekOfYear } from "@std/datetime/week-of-year";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(weekOfYear(new Date("2020-12-28T03:24:00")), 53);
 *
 * assertEquals(weekOfYear(new Date("2020-07-10T03:24:00")), 28);
 * ```
 */
export function weekOfYear(date: Date): number {
  const workingDate = new Date(
    Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()),
  );

  const day = workingDate.getUTCDay();

  const nearestThursday = workingDate.getUTCDate() +
    Day.Thu -
    (day === Day.Sun ? DAYS_PER_WEEK : day);

  workingDate.setUTCDate(nearestThursday);

  // Get first day of year
  const yearStart = new Date(Date.UTC(workingDate.getUTCFullYear(), 0, 1));

  // return the calculated full weeks to nearest Thursday
  return Math.ceil((workingDate.getTime() - yearStart.getTime() + DAY) / WEEK);
}

// denoCacheMetadata={"headers":{"server":"cloudflare","date":"Tue, 28 Jul 2026 12:31:15 GMT","etag":"\"e7ddbe2875f2d9f91807fff373f77784\"","x-jsr-backend":"modules","cache-control":"public, max-age=31536000, immutable","access-control-allow-origin":"*","set-cookie":"__cf_bm=1K9GG.ZJidn2cw.RPlcfyZjdBCGGHEcw3alyvz6LIks-1785241874.972591-1.0.1.1-UiwmnrHk46ztZaV7eBRNGtlcUu1NLTmR6xxsyBpijwViO_6vEzwqagQBO6AXz8CU4fJropQuUEb67EArP6eHJQDz5m.p4CwZiUWzX8fK7ey8KrvUgljWF6_PCobnE.7M; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cross-origin-resource-policy":"cross-origin","x-content-type-options":"nosniff","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-robots-tag":"noindex","cf-ray":"a223e6564f5f7db6-LAX","content-type":"text/typescript","vary":"Origin","content-length":"1333","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=KdPiej%2BVXLt0k8jMLWNb3czV8DYScFdhMoOyV%2Bc1BquDiQp%2FSA0RcvmfqQxNwQt3zFxp5HUMQzMh%2BxBPb5X9QcjOV2f4SPVky9GDXmd9FZCtP%2FZ9qSQF8fU%3D\"}]}","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","access-control-expose-headers":"*","alt-svc":"h3=\":443\"; ma=86400"},"url":"https://jsr.io/@std/datetime/0.224.5/week_of_year.ts","time":1785241875}