import { defineStore } from 'pinia'

import { api } from '../lib/api'
import {
  classifyPublicLoadError,
  createAwardsState,
  createEmptyAdminDashboard,
  createEmptyAdminOperationalSettings,
  createEmptyAdminRiskFlagsResponse,
  createEmptyAdminSeasonDetail,
  createEmptyAdminOptionalFeatureSettings,
  createEmptyAdminSiteSettings,
  createEmptyAdminTrackingRulesResponse,
  createEmptyAdminWorkflowRulesResponse,
  createEmptyArchive,
  createEmptyDatabaseHealth,
  createEmptyPublicSponsors,
  normalizeSeasonDetail,
} from './awards/defaults'
import type {
  ApproveNominationPayload,
  AddNominationLinkBlacklistEntryPayload,
  UpsertArchivedWinnerPayload,
  CreateSeasonPayload,
  CreateClipPayload,
  CreateNominationPayload,
  CreateShowactApplicationPayload,
  CreateVotePayload,
  ReopenRejectedNominationPayload,
  RejectNominationPayload,
  ResolveRiskFlagPayload,
  SetAwardResultPayload,
  AdminAuditQueryOptions,
  AdminRiskQueryOptions,
  UpdateSeasonSubcategoryTemplatesPayload,
  UpdateSeasonPayload,
  UpdateClipStatusPayload,
  UpdateNominationLinkBlacklistPayload,
  UpdateOptionalFeatureSettingsPayload,
  UpdateNominationTrackingReviewPayload,
  UpdateShowactStatusPayload,
  UpdateSiteSettingsPayload,
  UpdateTrackingReviewNotesPayload,
  UpdateTrackingRulesPayload,
  UpdateTrackingSourcePayload,
  UpdateWorkflowRulesPayload,
  UpsertCandidatePayload,
  UpsertCategoryPayload,
  UpsertCategoryGroupPayload,
  UpsertSponsorPayload,
} from '../types/awards'

interface AdminSeasonRefreshOptions {
  reloadAdmin?: boolean
  reloadHome?: boolean
}

export const useAwardsStore = defineStore('awards', {
  state: createAwardsState,
  actions: {
    async loadHomeData() {
      this.loading = true
      this.lastPublicError = null
      this.lastPublicErrorKind = null
      try {
        this.overview = await api.getOverview()
        this.categories = await api.getSeasonCategories(this.overview.year)
        await this.loadPublicSponsors(this.overview.year)
        const overviewArchiveYears = this.overview.archiveYears ?? []
        const initialArchiveYear = overviewArchiveYears[0]?.year ?? this.overview.year - 1
        this.archive = overviewArchiveYears.length > 0
          ? await api.getWinnerArchive(initialArchiveYear)
          : createEmptyArchive(initialArchiveYear)
        this.apiMode = 'api'
      } catch (error) {
        this.apiMode = 'fallback'
        const { message, kind } = classifyPublicLoadError(error)
        if (kind) {
          this.lastPublicError = message
          this.lastPublicErrorKind = kind
        }
      } finally {
        this.loading = false
      }
    },
    async loadArchive(year: number) {
      try {
        this.archive = await api.getWinnerArchive(year)
        this.apiMode = 'api'
      } catch {
        this.archive = createEmptyArchive(year)
      }
    },
    async loadPublicSponsors(year: number) {
      try {
        this.publicSponsors = await api.getPublicSponsors(year)
        return this.publicSponsors
      } catch {
        this.publicSponsors = createEmptyPublicSponsors(year)
        return this.publicSponsors
      }
    },
    async loadAdmin() {
      try {
        const [adminSeasons, adminSiteSettings, adminOptionalFeatureSettings, adminOperationalSettings, databaseHealth] = await Promise.all([
          api.getAdminSeasons(),
          api.getAdminSiteSettings().catch(() => createEmptyAdminSiteSettings()),
          api.getAdminOptionalFeatureSettings().catch(() => createEmptyAdminOptionalFeatureSettings()),
          api.getAdminOperationalSettings().catch(() => createEmptyAdminOperationalSettings()),
          api.getDatabaseHealth().catch(() => createEmptyDatabaseHealth()),
        ])

        this.adminSeasons = adminSeasons
        this.adminSiteSettings = adminSiteSettings
        this.adminOptionalFeatureSettings = adminOptionalFeatureSettings
        this.adminOperationalSettings = adminOperationalSettings
        this.databaseHealth = databaseHealth

        if (!this.adminSelectedSeasonId || !this.adminSeasons.some((season) => season.id === this.adminSelectedSeasonId)) {
          this.adminSelectedSeasonId = this.adminSeasons[0]?.id ?? null
        }

        if (this.adminSelectedSeasonId) {
          const [admin, seasonDetail, sponsors, showacts, adminWorkflowRules] = await Promise.all([
            api.getAdminDashboard(this.adminSelectedSeasonId),
            api.getAdminSeasonDetail(this.adminSelectedSeasonId),
            api.getAdminSponsors(this.adminSelectedSeasonId).catch(() => []),
            api.getAdminShowactApplications(this.adminSelectedSeasonId).catch(() => []),
            api.getAdminWorkflowRules(this.adminSelectedSeasonId).catch(() => createEmptyAdminWorkflowRulesResponse()),
          ])
          this.admin = admin
          this.adminSeasonDetail = normalizeSeasonDetail(seasonDetail)
          this.adminSponsors = sponsors
          this.adminShowactApplications = showacts
          this.adminWorkflowRules = adminWorkflowRules
        } else {
          this.admin = createEmptyAdminDashboard()
          this.adminSeasonDetail = createEmptyAdminSeasonDetail()
          this.adminSponsors = []
          this.adminShowactApplications = []
          this.adminWorkflowRules = createEmptyAdminWorkflowRulesResponse()
        }
        this.apiMode = 'api'
      } catch {
        this.apiMode = 'fallback'
        this.admin = createEmptyAdminDashboard()
        this.adminSeasons = []
        this.adminSeasonDetail = createEmptyAdminSeasonDetail()
        this.adminSiteSettings = createEmptyAdminSiteSettings()
        this.adminOperationalSettings = createEmptyAdminOperationalSettings()
        this.adminOptionalFeatureSettings = createEmptyAdminOptionalFeatureSettings()
        this.adminWorkflowRules = createEmptyAdminWorkflowRulesResponse()
        this.adminTrackingRules = createEmptyAdminTrackingRulesResponse()
        this.adminArchivedWinners = []
        this.adminRiskHistory = []
        this.adminRiskFlagsPage = createEmptyAdminRiskFlagsResponse()
        this.adminRiskHistoryPage = createEmptyAdminRiskFlagsResponse()
        this.adminSponsors = []
        this.adminShowactApplications = []
        this.databaseHealth = createEmptyDatabaseHealth()
        this.adminSelectedSeasonId = null
      }
    },
    async loadAdminContentWorkspace() {
      try {
        const [adminSiteSettings, adminOptionalFeatureSettings, adminOperationalSettings, databaseHealth] = await Promise.all([
          api.getAdminSiteSettings().catch(() => createEmptyAdminSiteSettings()),
          api.getAdminOptionalFeatureSettings().catch(() => createEmptyAdminOptionalFeatureSettings()),
          api.getAdminOperationalSettings().catch(() => createEmptyAdminOperationalSettings()),
          api.getDatabaseHealth().catch(() => createEmptyDatabaseHealth()),
        ])

        this.adminSiteSettings = adminSiteSettings
        this.adminOptionalFeatureSettings = adminOptionalFeatureSettings
        this.adminOperationalSettings = adminOperationalSettings
        this.databaseHealth = databaseHealth
        this.apiMode = 'api'
      } catch {
        this.apiMode = 'fallback'
        this.adminSiteSettings = createEmptyAdminSiteSettings()
        this.adminOperationalSettings = createEmptyAdminOperationalSettings()
        this.adminOptionalFeatureSettings = createEmptyAdminOptionalFeatureSettings()
        this.databaseHealth = createEmptyDatabaseHealth()
      }
    },
    async loadDatabaseHealth() {
      try {
        this.databaseHealth = await api.getDatabaseHealth()
        this.apiMode = 'api'
        return this.databaseHealth
      } catch (error) {
        this.databaseHealth = createEmptyDatabaseHealth()
        this.apiMode = 'fallback'
        throw error
      }
    },
    async loadAdminSeasonDetail(seasonId: number) {
      try {
        this.adminSelectedSeasonId = seasonId
        const [admin, seasonDetail, sponsors, showacts, adminWorkflowRules] = await Promise.all([
          api.getAdminDashboard(seasonId),
          api.getAdminSeasonDetail(seasonId),
          api.getAdminSponsors(seasonId).catch(() => []),
          api.getAdminShowactApplications(seasonId).catch(() => []),
          api.getAdminWorkflowRules(seasonId).catch(() => createEmptyAdminWorkflowRulesResponse()),
        ])
        this.admin = admin
        this.adminSeasonDetail = normalizeSeasonDetail(seasonDetail)
        this.adminSponsors = sponsors
        this.adminShowactApplications = showacts
        this.adminWorkflowRules = adminWorkflowRules
        this.apiMode = 'api'
      } catch {
        this.apiMode = 'fallback'
        this.admin = createEmptyAdminDashboard()
        this.adminSeasonDetail = createEmptyAdminSeasonDetail()
        this.adminSponsors = []
        this.adminShowactApplications = []
        this.adminWorkflowRules = createEmptyAdminWorkflowRulesResponse()
        this.adminArchivedWinners = []
      }
    },
    async initializeAdminWorkspace() {
      await this.loadAdmin()
      if (this.adminSelectedSeasonId && this.adminSeasonDetail.id !== this.adminSelectedSeasonId) {
        await this.loadAdminSeasonDetail(this.adminSelectedSeasonId)
      }
    },
    async refreshAdminSeasonWorkspace(seasonId: number, options: AdminSeasonRefreshOptions = {}) {
      this.adminSelectedSeasonId = seasonId
      if (options.reloadAdmin) {
        await this.loadAdmin()
      } else {
        await this.loadAdminSeasonDetail(seasonId)
      }

      if (options.reloadHome) {
        await this.loadHomeData()
      }
    },
    async refreshAfterSeasonListMutation(options: Pick<AdminSeasonRefreshOptions, 'reloadHome'> = {}) {
      await this.loadAdmin()
      if (options.reloadHome) {
        await this.loadHomeData()
      }
    },
    async loadAdminAuditEntries(limit = 200, query = '') {
      const auditEntries = await api.getAdminAuditEntries(limit, query)
      this.admin = { ...this.admin, auditEntries }
      return auditEntries
    },
    async loadAdminAuditEntriesPage(options: AdminAuditQueryOptions = {}, append = false) {
      const response = await api.getAdminAuditEntriesPage(options)
      this.admin = {
        ...this.admin,
        auditEntries: append ? [...this.admin.auditEntries, ...response.items] : response.items,
      }
      return response
    },
    async loadAdminRiskFlags(limit = 200, status = 'open', query = '') {
      const response = await this.loadAdminRiskFlagsPage({ limit, status, query })
      return response.items
    },
    async loadAdminRiskFlagsPage(options: AdminRiskQueryOptions = {}) {
      const response = await api.getAdminRiskFlagsPage(options)
      this.adminRiskFlagsPage = response
      if ((options.status ?? 'open') === 'open' && !options.reviewedOnly) {
        this.admin = { ...this.admin, riskFlags: response.items }
      }
      return response
    },
    async loadAdminRiskHistory(limit = 80, query = '') {
      const response = await this.loadAdminRiskHistoryPage({ limit, query })
      return response.items
    },
    async loadAdminRiskHistoryPage(options: AdminRiskQueryOptions = {}) {
      const response = await api.getAdminRiskFlagsPage({
        ...options,
        status: options.status ?? 'all',
        reviewedOnly: true,
      })
      this.adminRiskHistoryPage = response
      this.adminRiskHistory = response.items
      return response
    },
    setAdminSeason(seasonId: number) {
      this.adminSelectedSeasonId = seasonId
    },
    submitNomination(payload: CreateNominationPayload) {
      return api.submitNomination(payload)
    },
    submitVote(payload: CreateVotePayload) {
      return api.submitVote(payload)
    },
    submitClip(payload: CreateClipPayload) {
      return api.submitClip(payload)
    },
    submitShowactApplication(payload: CreateShowactApplicationPayload) {
      return api.submitShowactApplication(payload)
    },
    async loadAdminExtras(seasonId?: number | null) {
      const resolvedSeasonId = seasonId ?? this.adminSelectedSeasonId
      if (!resolvedSeasonId) {
        this.adminSponsors = []
        this.adminShowactApplications = []
        return { sponsors: this.adminSponsors, showacts: this.adminShowactApplications }
      }

      const [sponsors, showacts] = await Promise.all([
        api.getAdminSponsors(resolvedSeasonId),
        api.getAdminShowactApplications(resolvedSeasonId),
      ])
      this.adminSponsors = sponsors
      this.adminShowactApplications = showacts
      return { sponsors, showacts }
    },
    async createAdminSponsor(seasonId: number, payload: UpsertSponsorPayload) {
      const result = await api.createAdminSponsor(seasonId, payload)
      await Promise.all([this.loadAdminExtras(seasonId), this.loadPublicSponsors(this.overview.year)])
      return result
    },
    async loadAdminArchivedWinners() {
      this.adminArchivedWinners = await api.getAdminArchivedWinners()
      return this.adminArchivedWinners
    },
    async createAdminArchivedWinner(payload: UpsertArchivedWinnerPayload) {
      const result = await api.createAdminArchivedWinner(payload)
      await Promise.all([this.loadAdminArchivedWinners(), this.loadHomeData()])
      return result
    },
    async updateAdminArchivedWinner(archivedWinnerId: number, payload: UpsertArchivedWinnerPayload) {
      const result = await api.updateAdminArchivedWinner(archivedWinnerId, payload)
      await Promise.all([this.loadAdminArchivedWinners(), this.loadHomeData()])
      return result
    },
    async deleteAdminArchivedWinner(archivedWinnerId: number) {
      const result = await api.deleteAdminArchivedWinner(archivedWinnerId)
      await Promise.all([this.loadAdminArchivedWinners(), this.loadHomeData()])
      return result
    },
    async updateAdminSponsor(sponsorId: number, seasonId: number, payload: UpsertSponsorPayload) {
      const result = await api.updateAdminSponsor(sponsorId, payload)
      await Promise.all([this.loadAdminExtras(seasonId), this.loadPublicSponsors(this.overview.year)])
      return result
    },
    async deleteAdminSponsor(sponsorId: number, seasonId: number) {
      const result = await api.deleteAdminSponsor(sponsorId)
      await Promise.all([this.loadAdminExtras(seasonId), this.loadPublicSponsors(this.overview.year)])
      return result
    },
    async updateAdminShowactStatus(applicationId: number, seasonId: number, payload: UpdateShowactStatusPayload) {
      const result = await api.updateAdminShowactStatus(applicationId, payload)
      await this.loadAdminExtras(seasonId)
      return result
    },
    async deleteAdminShowactApplication(applicationId: number, seasonId: number) {
      const result = await api.deleteAdminShowactApplication(applicationId)
      await this.loadAdminExtras(seasonId)
      return result
    },
    async updateAdminSeason(seasonId: number, payload: UpdateSeasonPayload) {
      const result = await api.updateAdminSeason(seasonId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true, reloadHome: true })
      return result
    },
    async createAdminSeason(payload: CreateSeasonPayload) {
      const result = await api.createAdminSeason(payload)
      await this.refreshAdminSeasonWorkspace(result.seasonId, { reloadAdmin: true, reloadHome: true })
      return result
    },
    async deleteAdminSeason(seasonId: number) {
      const result = await api.deleteAdminSeason(seasonId)
      await this.refreshAfterSeasonListMutation({ reloadHome: true })
      return result
    },
    async createAdminCategory(seasonId: number, payload: UpsertCategoryPayload) {
      const result = await api.createAdminCategory(seasonId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async updateAdminCategory(categoryId: number, seasonId: number, payload: UpsertCategoryPayload) {
      const result = await api.updateAdminCategory(categoryId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async updateAdminSeasonSubcategoryTemplates(seasonId: number, payload: UpdateSeasonSubcategoryTemplatesPayload) {
      const result = await api.updateAdminSeasonSubcategoryTemplates(seasonId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async createAdminCategoryGroup(seasonId: number, payload: UpsertCategoryGroupPayload) {
      const result = await api.createAdminCategoryGroup(seasonId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async updateAdminCategoryGroup(seasonId: number, groupName: string, payload: UpsertCategoryGroupPayload) {
      const result = await api.updateAdminCategoryGroup(seasonId, groupName, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async deleteAdminCategoryGroup(seasonId: number, groupName: string) {
      const result = await api.deleteAdminCategoryGroup(seasonId, groupName)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async createAdminCandidate(seasonId: number, payload: UpsertCandidatePayload) {
      const result = await api.createAdminCandidate(seasonId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async updateAdminCandidate(candidateId: number, seasonId: number, payload: UpsertCandidatePayload) {
      const result = await api.updateAdminCandidate(candidateId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async deleteAdminCandidate(candidateId: number, seasonId: number) {
      const result = await api.deleteAdminCandidate(candidateId)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async deleteAdminCategory(categoryId: number, seasonId: number) {
      const result = await api.deleteAdminCategory(categoryId)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadHome: true })
      return result
    },
    async deleteAdminClip(clipId: number, seasonId: number) {
      const result = await api.deleteAdminClip(clipId)
      await this.refreshAdminSeasonWorkspace(seasonId)
      return result
    },
    async updateAdminClipStatus(clipId: number, seasonId: number, payload: UpdateClipStatusPayload) {
      const result = await api.updateAdminClipStatus(clipId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true })
      return result
    },
    async bulkUpdateAdminClipStatus(clipIds: number[], seasonId: number, status: 'approved' | 'rejected', reviewNote?: string) {
      await Promise.allSettled(clipIds.map((id) => api.updateAdminClipStatus(id, { status, reviewNote })))
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true })
    },
    async setAdminResult(seasonId: number, payload: SetAwardResultPayload) {
      const result = await api.setAdminResult(seasonId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true, reloadHome: true })
      return result
    },
    async deleteAdminResult(resultId: number, seasonId: number) {
      const result = await api.deleteAdminResult(resultId)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true, reloadHome: true })
      return result
    },
    async publishAdminWinners(seasonId: number) {
      const result = await api.publishAdminWinners(seasonId)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true, reloadHome: true })
      return result
    },
    async unpublishAdminWinners(seasonId: number) {
      const result = await api.unpublishAdminWinners(seasonId)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true, reloadHome: true })
      return result
    },
    async approveAdminNomination(nominationId: number, seasonId: number, payload: ApproveNominationPayload) {
      const result = await api.approveAdminNomination(nominationId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true, reloadHome: true })
      return result
    },
    async rejectAdminNomination(nominationId: number, seasonId: number, payload: RejectNominationPayload) {
      const result = await api.rejectAdminNomination(nominationId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true })
      return result
    },
    async reopenRejectedAdminNomination(nominationId: number, seasonId: number, payload: ReopenRejectedNominationPayload = {}) {
      const result = await api.reopenRejectedAdminNomination(nominationId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true })
      return result
    },
    async bulkRejectAdminNominations(nominationIds: number[], seasonId: number, reviewNote?: string) {
      await Promise.allSettled(nominationIds.map((id) => api.rejectAdminNomination(id, { reviewNote })))
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true })
    },
    loadAdminNominationLinkBlacklist() {
      return api.getAdminNominationLinkBlacklist()
    },
    updateAdminNominationLinkBlacklist(payload: UpdateNominationLinkBlacklistPayload) {
      return api.updateAdminNominationLinkBlacklist(payload)
    },
    addAdminNominationLinkBlacklistEntry(payload: AddNominationLinkBlacklistEntryPayload) {
      return api.addAdminNominationLinkBlacklistEntry(payload)
    },
    async resolveRiskFlag(riskFlagId: number, payload: ResolveRiskFlagPayload) {
      const result = await api.resolveRiskFlag(riskFlagId, payload)
      await Promise.all([
        this.loadAdminRiskFlagsPage({
          limit: this.adminRiskFlagsPage.limit || 25,
          offset: this.adminRiskFlagsPage.offset,
          status: 'open',
        }),
        this.loadAdminRiskHistoryPage({
          limit: this.adminRiskHistoryPage.limit || 25,
          offset: this.adminRiskHistoryPage.offset,
        }),
      ])
      return result
    },
    async bulkResolveRiskFlags(payload: import('../types/awards').BulkResolveRiskFlagsPayload) {
      const result = await api.bulkResolveRiskFlags(payload)
      await Promise.all([
        this.loadAdminRiskFlagsPage({
          limit: this.adminRiskFlagsPage.limit || 25,
          offset: this.adminRiskFlagsPage.offset,
          status: 'open',
        }),
        this.loadAdminRiskHistoryPage({
          limit: this.adminRiskHistoryPage.limit || 25,
          offset: this.adminRiskHistoryPage.offset,
        }),
      ])
      return result
    },
    async loadAdminRiskRules() {
      return api.getAdminRiskRules()
    },
    async updateAdminRiskRules(payload: import('../types/awards').UpdateRiskRulesPayload) {
      return api.updateAdminRiskRules(payload)
    },
    async loadAdminOptionalFeatureSettings() {
      this.adminOptionalFeatureSettings = await api.getAdminOptionalFeatureSettings()
      return this.adminOptionalFeatureSettings
    },
    async updateAdminOptionalFeatureSettings(payload: UpdateOptionalFeatureSettingsPayload) {
      this.adminOptionalFeatureSettings = await api.updateAdminOptionalFeatureSettings(payload)
      await this.loadHomeData()
      return this.adminOptionalFeatureSettings
    },
    async loadAdminWorkflowRules() {
      if (!this.adminSelectedSeasonId) {
        this.adminWorkflowRules = createEmptyAdminWorkflowRulesResponse()
        return this.adminWorkflowRules
      }

      this.adminWorkflowRules = await api.getAdminWorkflowRules(this.adminSelectedSeasonId)
      return this.adminWorkflowRules
    },
    async updateAdminWorkflowRules(payload: UpdateWorkflowRulesPayload) {
      if (!this.adminSelectedSeasonId) {
        throw new Error('Kein Award-Jahr fuer Workflow-Regeln ausgewaehlt.')
      }

      this.adminWorkflowRules = await api.updateAdminWorkflowRules(this.adminSelectedSeasonId, payload)
      return this.adminWorkflowRules
    },
    async loadAdminTrackingRules() {
      this.adminTrackingRules = await api.getAdminTrackingRules()
      return this.adminTrackingRules
    },
    async updateAdminTrackingRules(payload: UpdateTrackingRulesPayload) {
      this.adminTrackingRules = await api.updateAdminTrackingRules(payload)
      if (this.adminSelectedSeasonId) {
        await this.loadAdminSeasonDetail(this.adminSelectedSeasonId)
      }
      return this.adminTrackingRules
    },
    async updateAdminTrackingSource(payload: UpdateTrackingSourcePayload) {
      this.adminTrackingRules = await api.updateAdminTrackingSource(payload)
      if (this.adminSelectedSeasonId) {
        await this.loadAdminSeasonDetail(this.adminSelectedSeasonId)
      }
      return this.adminTrackingRules
    },
    async updateAdminTrackingReviewNotes(payload: UpdateTrackingReviewNotesPayload) {
      this.adminTrackingRules = await api.updateAdminTrackingReviewNotes(payload)
      if (this.adminSelectedSeasonId) {
        await this.loadAdminSeasonDetail(this.adminSelectedSeasonId)
      }
      return this.adminTrackingRules
    },
    async updateNominationTrackingReview(nominationId: number, seasonId: number, payload: UpdateNominationTrackingReviewPayload) {
      const result = await api.updateNominationTrackingReview(nominationId, payload)
      await this.refreshAdminSeasonWorkspace(seasonId, { reloadAdmin: true })
      return result
    },
    async updateAdminSiteSettings(payload: UpdateSiteSettingsPayload) {
      const result = await api.updateAdminSiteSettings(payload)
      this.adminSiteSettings = await api.getAdminSiteSettings()
      await this.loadHomeData()
      return result
    },
    async uploadAdminHostImage(file: File) {
      this.adminSiteSettings = await api.uploadAdminHostImage(file)
      await this.loadHomeData()
      return this.adminSiteSettings
    },
  },
})

export type AwardsStore = ReturnType<typeof useAwardsStore>
