<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">

<cffunction name="apiAbort" access="public" returntype="void" output="true">
  <cfargument name="payload" type="struct" required="true">
  <cfcontent type="application/json; charset=utf-8">
  <cfoutput>#serializeJSON(arguments.payload)#</cfoutput>
  <cfabort>
</cffunction>

<cftry>
  <!--- Create Stations table if it doesn't exist --->
  <cfset queryTimed("
    CREATE TABLE IF NOT EXISTS Stations (
      ID INT AUTO_INCREMENT PRIMARY KEY,
      BusinessID INT NOT NULL,
      Name VARCHAR(100) NOT NULL,
      Color VARCHAR(7) DEFAULT '##666666',
      SortOrder INT DEFAULT 0,
      IsActive TINYINT(1) DEFAULT 1,
      AddedOn DATETIME DEFAULT NOW(),
      FOREIGN KEY (BusinessID) REFERENCES Businesses(ID)
    )
  ", [], { datasource = "payfrit" })>

  <!--- Add StationID column to Items table if it doesn't exist --->
  <cftry>
    <cfset queryTimed("
      ALTER TABLE Items ADD COLUMN StationID INT DEFAULT NULL
    ", [], { datasource = "payfrit" })>
    <cfset stationColumnAdded = true>
    <cfcatch>
      <!--- Column likely already exists --->
      <cfset stationColumnAdded = false>
    </cfcatch>
  </cftry>

  <!--- Add foreign key if column was just added --->
  <cfif stationColumnAdded>
    <cftry>
      <cfset queryTimed("
        ALTER TABLE Items ADD FOREIGN KEY (StationID) REFERENCES Stations(ID)
      ", [], { datasource = "payfrit" })>
      <cfcatch></cfcatch>
    </cftry>
  </cfif>

  <!--- Create some default stations for business 1 (In and Out Burger) if none exist --->
  <cfset qCheck = queryTimed("
    SELECT COUNT(*) AS cnt FROM Stations WHERE BusinessID = 1
  ", [], { datasource = "payfrit" })>

  <cfif qCheck.cnt EQ 0>
    <cfset queryTimed("
      INSERT INTO Stations (BusinessID, Name, Color, SortOrder) VALUES
      (1, 'Grill', '##FF5722', 1),
      (1, 'Fry', '##FFC107', 2),
      (1, 'Drinks', '##2196F3', 3),
      (1, 'Expo', '##4CAF50', 4)
    ", [], { datasource = "payfrit" })>
    <cfset defaultStationsCreated = true>
  <cfelse>
    <cfset defaultStationsCreated = false>
  </cfif>

  <cfset apiAbort({
    "OK": true,
    "MESSAGE": "Stations setup complete",
    "StationColumnAdded": stationColumnAdded,
    "DefaultStationsCreated": defaultStationsCreated
  })>

  <cfcatch>
    <cfset apiAbort({
      "OK": false,
      "ERROR": "setup_failed",
      "MESSAGE": cfcatch.message,
      "DETAIL": cfcatch.detail
    })>
  </cfcatch>
</cftry>
