// SPDX-FileCopyrightText: 2025 Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache-2.0

import { ChargingStationDetail } from '@lib/client/pages/charging-stations/detail/charging.station.detail';

type PageProps = {
  params: Promise<{ id: string }>;
};

async function fetchStation(id: string) {
  try {
    const res = await fetch('http://cariflex-hasura:8080/v1/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-hasura-admin-secret': process.env.HASURA_ADMIN_SECRET || '',
      },
      body: JSON.stringify({
        query: `
          query GetStation($id: String!) {
            ChargingStations(where: {id: {_eq: $id}}, limit: 1) {
              id
              tenantId
              ocppConnectionName
              isOnline
              protocol
              locationId
              chargePointVendor
              chargePointModel
              firmwareVersion
              createdAt
              updatedAt
              floorLevel
              parkingRestrictions
              capabilities
              coordinates
              use16StatusNotification0
              location { id name address city postalCode state country coordinates createdAt updatedAt }
              evses { id stationId evseId evseTypeId physicalReference removed createdAt updatedAt }
              variableAttributes { id stationId variableId value dataType }
              latestStatusNotifications { id stationId statusNotificationId updatedAt createdAt StatusNotification { connectorId connectorStatus createdAt evseId id stationId timestamp updatedAt } }
              transactions(where: {isActive: {_eq: true}}) { id stationId timeSpentCharging isActive chargingState stoppedReason transactionId evseId remoteStartId totalKwh createdAt updatedAt }
              connectors { id stationId evseId connectorId status type maximumPowerWatts maximumAmperage maximumVoltage format powerType termsAndConditionsUrl tariffId errorCode timestamp info vendorId vendorErrorCode createdAt updatedAt }
            }
          }
        `,
        variables: { id },
      }),
      cache: 'no-store',
    });
    const data = await res.json();
    if (data.errors) {
      console.error('GraphQL errors:', data.errors);
      return null;
    }
    return data?.data?.ChargingStations?.[0] || null;
  } catch (err) {
    console.error('Fetch error:', err);
    return null;
  }
}

export default async function ShowChargingStationPage({ params }: PageProps) {
  const { id } = await params;
  const station = await fetchStation(id);
  return <ChargingStationDetail params={{ id, station }} />;
}
