import { request } from '@/utils/request'
import type { PageParams, PageResult } from '@/types/api'

export type CouponType = 0 | 1 | 2
export type CouponStatus = 0 | 1 | 2
export type UserCouponStatus = 0 | 1 | 2 | 3

export interface CouponItem {
  id: number
  name: string
  type: CouponType
  typeText: string
  amount: number
  minAmount: number
  maxDiscount: number
  total: number
  remain: number
  received: number
  perLimit: number
  status: CouponStatus
  statusText: string
  startTime: string
  endTime: string
  validDays?: number
  description?: string
  createTime: string
  updateTime: string
}

export interface CouponSavePayload {
  id?: number
  name: string
  type: CouponType
  amount: number
  minAmount: number
  maxDiscount: number
  total: number
  perLimit: number
  status: CouponStatus
  startTime: string
  endTime: string
  validDays?: number | null
  description?: string
}

export interface CouponPageQuery extends PageParams {
  keyword?: string
  type?: CouponType
  status?: CouponStatus
}

export interface UserCouponRecord {
  id: number
  userId: number
  username: string
  nickname: string
  couponId: number
  couponName: string
  couponType: CouponType
  status: UserCouponStatus
  statusText: string
  orderId?: number
  receiveTime: string
  useTime?: string
  expireTime: string
}

export interface UserCouponPageQuery extends PageParams {
  couponId?: number
  userId?: number
  status?: UserCouponStatus
  keyword?: string
}

export function getCouponPageApi(params: CouponPageQuery) {
  return request<PageResult<CouponItem>>({
    url: '/api/admin/coupon/page',
    method: 'GET',
    params
  })
}

export function getCouponDetailApi(id: number) {
  return request<CouponItem>({
    url: `/api/admin/coupon/${id}`,
    method: 'GET'
  })
}

export function createCouponApi(data: CouponSavePayload) {
  return request<number>({
    url: '/api/admin/coupon',
    method: 'POST',
    data
  })
}

export function updateCouponApi(data: CouponSavePayload) {
  return request<void>({
    url: '/api/admin/coupon',
    method: 'PUT',
    data
  })
}

export function deleteCouponApi(id: number) {
  return request<void>({
    url: `/api/admin/coupon/${id}`,
    method: 'DELETE'
  })
}

export function updateCouponStatusApi(id: number, status: CouponStatus) {
  return request<void>({
    url: `/api/admin/coupon/${id}/status/${status}`,
    method: 'PUT'
  })
}

export function getUserCouponRecordPageApi(params: UserCouponPageQuery) {
  return request<PageResult<UserCouponRecord>>({
    url: '/api/admin/coupon/record/page',
    method: 'GET',
    params
  })
}

export function getCouponRecordsApi(id: number, params: Omit<UserCouponPageQuery, 'couponId'>) {
  return request<PageResult<UserCouponRecord>>({
    url: `/api/admin/coupon/${id}/records`,
    method: 'GET',
    params
  })
}
