package com.ffii.fpsms.modules.common.scheduler.web

import com.ffii.fpsms.modules.common.SettingNames
import com.ffii.fpsms.modules.common.scheduler.service.SchedulerService
import com.ffii.fpsms.modules.settings.service.SettingsService
import jakarta.validation.Valid
import org.springframework.format.annotation.DateTimeFormat
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.time.LocalDate


@RestController
@RequestMapping("/scheduler")
class SchedulerController(
    val schedulerService: SchedulerService,
    val settingsService: SettingsService
) {
    @GetMapping("/testDetailedProd")
    fun testDetailedProd(): Any {
        schedulerService.getDetailedProdSchedule()
        return 200
    }

    // Cron Settings
    @GetMapping("/updateSetting/poCron")
    fun schedulePo(@RequestParam @Valid newCron: String) {
        settingsService.update(SettingNames.SCHEDULE_M18_PO, newCron);
        schedulerService.scheduleM18PoTask()
    }

    @GetMapping("/trigger/po")
    fun triggerPo(): String {
        schedulerService.getM18Po()
        return "M18 PO Sync Triggered Successfully"
    }

    @GetMapping("/trigger/do1")
    fun triggerDo1(): String {
        schedulerService.getM18Dos1()
        return "M18 DO1 Sync Triggered Successfully"
    }

    /** Manual DO1 catch-up for a fixed dDate (production only). Skips existing local DOs by default. */
    @GetMapping("/trigger/do1-catchup")
    fun triggerDo1CatchUp(
        @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) dDate: LocalDate,
        @RequestParam(required = false, defaultValue = "true") skipExistingDo: Boolean = true,
    ): String {
        schedulerService.runDo1CatchUp(dDate, skipExistingDo = skipExistingDo)
        return "M18 DO1 catch-up triggered for dDate=$dDate skipExistingDo=$skipExistingDo"
    }

    @GetMapping("/trigger/do2")
    fun triggerDo2(): String {
        schedulerService.getM18Dos2()
        return "M18 DO2 Sync Triggered Successfully"
    }

    /** Manual test: push all FPSMS BOMs to M18 udfBomForShop ([SettingNames.M18_BOM_SHOP_SYNC_ENABLED] must still be true). */
    @GetMapping("/trigger/bom-shop-sync-all")
    fun triggerBomShopSyncAll(): String {
        schedulerService.getM18BomShopPushAllBoms()
        return "M18 BOM Shop (all BOMs) sync triggered (see scheduler_sync_log type M18_BOM_SHOP)"
    }

    @GetMapping("/updateSetting/bomShopCron")
    fun scheduleBomShop(@RequestParam @Valid newCron: String) {
        settingsService.update(SettingNames.SCHEDULE_M18_BOM_SHOP, newCron)
        schedulerService.scheduleM18BomShop()
    }

    @GetMapping("/trigger/master-data")
    fun triggerMasterData(): String {
        schedulerService.getM18MasterData()
        return "M18 Master Data Sync Triggered Successfully"
    }

    @GetMapping("/trigger/m18-units")
    fun triggerM18Units(): String {
        schedulerService.getM18Units()
        return "M18 units sync (/search/search?stSearch=unit) triggered"
    }

    @GetMapping("/trigger/grn-code-sync")
    fun triggerGrnCodeSync(): String {
        schedulerService.syncGrnCodesFromM18()
        return "M18 GRN code sync (read/an) triggered"
    }

    @GetMapping("/trigger/inventory-lot-expiry")
    fun triggerInventoryLotExpiry(): String {
        schedulerService.markExpiredInventoryLotLinesAsUnavailable()
        return "Inventory lot expiry status update triggered"
    }

    @GetMapping("/trigger/post-completed-dn-grn")
    fun triggerPostCompletedDnGrn(
        @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) receiptDate: LocalDate? = null,
        @RequestParam(required = false, defaultValue = "0") skipFirst: Int = 0,
        @RequestParam(required = false) limitToFirst: Int? = null,
    ): String {
        schedulerService.getPostCompletedDnAndProcessGrn(receiptDate = receiptDate, skipFirst = skipFirst, limitToFirst = limitToFirst)
        return "Post completed DN and process GRN triggered"
    }

    @GetMapping("/refresh-cron")
    fun refreshCron(): String {
        schedulerService.init()
        return "Cron Schedules Refreshed from Database"
    }
    @GetMapping("/trigger/jo-plan-start")
    fun triggerJoPlanStart(): String {
        schedulerService.runJobOrderPlanStartAuto()
        return "Job order plan-start auto triggered"
    }

    /** Run M18 sync health checks now (same as periodic SMS watchdog). Returns alert messages (empty = OK). */
    @GetMapping("/trigger/sync-alert-check")
    fun triggerSyncAlertCheck(): List<String> {
        return schedulerService.runSyncAlertCheckNow()
    }

    /**
     * Send a Twilio WhatsApp template test (same API as Twilio console curl).
     * Example: ?var1=12/1&var2=3pm — omit params to use today's date and current time.
     */
    @GetMapping("/trigger/sync-alert-test-whatsapp")
    fun triggerSyncAlertTestWhatsApp(
        @RequestParam(required = false) var1: String?,
        @RequestParam(required = false) var2: String?,
    ): String {
        return schedulerService.sendSyncAlertTestWhatsApp(var1, var2)
    }

    /** Test Office 365 / SMTP email (uses MAIL.smtp.* from settings). Optional message and subject. */
    @GetMapping("/trigger/sync-alert-test-email")
    fun triggerSyncAlertTestEmail(
        @RequestParam(required = false) message: String?,
        @RequestParam(required = false) subject: String?,
    ): String {
        return schedulerService.sendSyncAlertTestEmail(message, subject)
    }
}