import _ from "lodash";

import Request from "@/lib/request/Request.ts";
import { generateVideo } from "@/api/controllers/video.ts";
import { tokenSplit } from "@/api/controllers/core.ts";
import util from "@/lib/util.ts";

export default {
  prefix: "/v1/video",

  post: {
    "/generations": async (request: Request) => {
      request
        .validate("body.model", v => _.isUndefined(v) || _.isString(v))
        .validate("body.prompt", _.isString)
        .validate("body.image", v => _.isUndefined(v) || _.isString(v))
        .validate("body.width", v => _.isUndefined(v) || _.isFinite(v))
        .validate("body.height", v => _.isUndefined(v) || _.isFinite(v))
        .validate("body.duration", v => _.isUndefined(v) || _.isFinite(v))
        .validate("headers.authorization", _.isString);
      // refresh_token切分
      const tokens = tokenSplit(request.headers.authorization);
      // 随机挑选一个refresh_token
      const token = _.sample(tokens);
      const {
        model,
        prompt,
        width,
        height,
        image,
        duration,
      } = request.body;
      const imageUrls = await generateVideo(model, prompt, {
        width,
        height,
        imgURL:image,
        duration:duration*1000,
      }, token);
      let data = [];
      data = imageUrls.map((url) => ({
        url,
      }));
      return {
        created: util.unixTimestamp(),
        data,
      };
    },
  },
};
