import { z } from 'zod'
import { router, adminProcedure, protectedProcedure } from '../trpc'
import {
  createIntent,
  cancelIntent,
  getPendingIntentsForRound,
  getPendingIntentsForMember,
  getIntentsForRound,
} from '@/server/services/assignment-intent'

const intentSourceEnum = z.enum(['INVITE', 'ADMIN', 'SYSTEM'])

export const assignmentIntentRouter = router({
  /**
   * Create an assignment intent (pre-assignment signal).
   */
  create: adminProcedure
    .input(
      z.object({
        juryGroupMemberId: z.string(),
        roundId: z.string(),
        projectId: z.string(),
        source: intentSourceEnum.default('ADMIN'),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      return createIntent({
        juryGroupMemberId: input.juryGroupMemberId,
        roundId: input.roundId,
        projectId: input.projectId,
        source: input.source,
        actorId: ctx.user.id,
      })
    }),

  /**
   * List all intents for a round (all statuses).
   */
  listForRound: adminProcedure
    .input(z.object({ roundId: z.string() }))
    .query(async ({ input }) => {
      return getIntentsForRound(input.roundId)
    }),

  /**
   * List pending intents for a round.
   */
  listPendingForRound: adminProcedure
    .input(z.object({ roundId: z.string() }))
    .query(async ({ input }) => {
      return getPendingIntentsForRound(input.roundId)
    }),

  /**
   * List pending intents for a specific member in a round.
   * Protected (not admin-only) so jurors can see their own intents.
   */
  listForMember: protectedProcedure
    .input(
      z.object({
        juryGroupMemberId: z.string(),
        roundId: z.string(),
      }),
    )
    .query(async ({ input }) => {
      return getPendingIntentsForMember(input.juryGroupMemberId, input.roundId)
    }),

  /**
   * Cancel a pending intent.
   */
  cancel: adminProcedure
    .input(
      z.object({
        id: z.string(),
        reason: z.string().min(1),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      return cancelIntent(input.id, input.reason, ctx.user.id)
    }),
})
