const express = require('express');

const ProjectsService = require('../services/projects');
const ProjectsDBApi = require('../db/api/projects');
const { wrapAsync, isUuidV4 } = require('../helpers');

const router = express.Router();

const { parse } = require('json2csv');

const { checkCrudPermissions } = require('../middlewares/check-permissions');

router.use(checkCrudPermissions('projects'));

/**
 *  @swagger
 *  components:
 *    schemas:
 *      Projects:
 *        type: object
 *        properties:
 
 *          name:
 *            type: string
 *            default: name
 *          slug:
 *            type: string
 *            default: slug
 *          description:
 *            type: string
 *            default: description
 *          logo_url:
 *            type: string
 *            default: logo_url
 *          favicon_url:
 *            type: string
 *            default: favicon_url
 *          og_image_url:
 *            type: string
 *            default: og_image_url



 *
 */

/**
 *  @swagger
 * tags:
 *   name: Projects
 *   description: The Projects managing API
 */

/**
 *  @swagger
 *  /api/projects:
 *    post:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Add new item
 *      description: Add new item
 *      requestBody:
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              properties:
 *                data:
 *                  description: Data of the updated item
 *                  type: object
 *                  $ref: "#/components/schemas/Projects"
 *      responses:
 *        200:
 *          description: The item was successfully added
 *          content:
 *            application/json:
 *              schema:
 *                $ref: "#/components/schemas/Projects"
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        405:
 *          description: Invalid input data
 *        500:
 *          description: Some server error
 */
router.post(
  '/',
  wrapAsync(async (req, res) => {
    const referer =
      req.headers.referer ||
      `${req.protocol}://${req.hostname}${req.originalUrl}`;
    const link = new URL(referer);
    const payload = await ProjectsService.create(
      req.body.data,
      req.currentUser,
      true,
      link.host,
    );
    res.status(200).send(payload);
  }),
);

router.post(
  '/:id/clone',
  wrapAsync(async (req, res) => {
    if (!isUuidV4(req.params.id)) {
      return res.status(400).send('Invalid project id');
    }

    const payload = await ProjectsService.cloneFromProject(
      req.params.id,
      req.currentUser,
    );
    res.status(200).send(payload);
  }),
);

/**
 * @swagger
 * /api/budgets/bulk-import:
 *  post:
 *    security:
 *      - bearerAuth: []
 *    tags: [Projects]
 *    summary: Bulk import items
 *    description: Bulk import items
 *    requestBody:
 *      required: true
 *      content:
 *        application/json:
 *         schema:
 *          properties:
 *            data:
 *              description: Data of the updated items
 *              type: array
 *              items:
 *                $ref: "#/components/schemas/Projects"
 *    responses:
 *      200:
 *        description: The items were successfully imported
 *    content:
 *      application/json:
 *        schema:
 *          $ref: "#/components/schemas/Projects"
 *      401:
 *        $ref: "#/components/responses/UnauthorizedError"
 *      405:
 *        description: Invalid input data
 *      500:
 *        description: Some server error
 *
 */
router.post(
  '/bulk-import',
  wrapAsync(async (req, res) => {
    const referer =
      req.headers.referer ||
      `${req.protocol}://${req.hostname}${req.originalUrl}`;
    const link = new URL(referer);
    await ProjectsService.bulkImport(req, res, true, link.host);
    const payload = true;
    res.status(200).send(payload);
  }),
);

/**
 *  @swagger
 *  /api/projects/{id}:
 *    put:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Update the data of the selected item
 *      description: Update the data of the selected item
 *      parameters:
 *        - in: path
 *          name: id
 *          description: Item ID to update
 *          required: true
 *          schema:
 *            type: string
 *      requestBody:
 *        description: Set new item data
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              properties:
 *                id:
 *                  description: ID of the updated item
 *                  type: string
 *                data:
 *                  description: Data of the updated item
 *                  type: object
 *                  $ref: "#/components/schemas/Projects"
 *              required:
 *                - id
 *      responses:
 *        200:
 *          description: The item data was successfully updated
 *          content:
 *            application/json:
 *              schema:
 *                $ref: "#/components/schemas/Projects"
 *        400:
 *          description: Invalid ID supplied
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Item not found
 *        500:
 *          description: Some server error
 */
router.put(
  '/:id',
  wrapAsync(async (req, res) => {
    await ProjectsService.update(req.body.data, req.body.id, req.currentUser);
    const payload = true;
    res.status(200).send(payload);
  }),
);

/**
 * @swagger
 *  /api/projects/{id}:
 *    delete:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Delete the selected item
 *      description: Delete the selected item
 *      parameters:
 *        - in: path
 *          name: id
 *          description: Item ID to delete
 *          required: true
 *          schema:
 *            type: string
 *      responses:
 *        200:
 *          description: The item was successfully deleted
 *          content:
 *            application/json:
 *              schema:
 *                $ref: "#/components/schemas/Projects"
 *        400:
 *          description: Invalid ID supplied
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Item not found
 *        500:
 *          description: Some server error
 */
router.delete(
  '/:id',
  wrapAsync(async (req, res) => {
    await ProjectsService.remove(req.params.id, req.currentUser);
    const payload = true;
    res.status(200).send(payload);
  }),
);

/**
 *  @swagger
 *  /api/projects/deleteByIds:
 *    post:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Delete the selected item list
 *      description: Delete the selected item list
 *      requestBody:
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              properties:
 *                ids:
 *                  description: IDs of the updated items
 *                  type: array
 *      responses:
 *        200:
 *          description: The items was successfully deleted
 *          content:
 *            application/json:
 *              schema:
 *                $ref: "#/components/schemas/Projects"
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Items not found
 *        500:
 *          description: Some server error
 */
router.post(
  '/deleteByIds',
  wrapAsync(async (req, res) => {
    await ProjectsService.deleteByIds(req.body.data, req.currentUser);
    const payload = true;
    res.status(200).send(payload);
  }),
);

/**
 *  @swagger
 *  /api/projects:
 *    get:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Get all projects
 *      description: Get all projects
 *      responses:
 *        200:
 *          description: Projects list successfully received
 *          content:
 *            application/json:
 *              schema:
 *                type: array
 *                items:
 *                  $ref: "#/components/schemas/Projects"
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Data not found
 *        500:
 *          description: Some server error
 */
router.get(
  '/',
  wrapAsync(async (req, res) => {
    const filetype = req.query.filetype;

    const currentUser = req.currentUser;
    const runtimeContext = req.runtimeContext;
    const payload = await ProjectsDBApi.findAll(req.query, {
      currentUser,
      runtimeContext,
    });
    if (filetype && filetype === 'csv') {
      const fields = [
        'id',
        'name',
        'slug',
        'description',
        'logo_url',
        'favicon_url',
        'og_image_url',
      ];
      const opts = { fields };
      try {
        const csv = parse(payload.rows, opts);
        res.status(200).attachment(csv);
        res.send(csv);
      } catch (err) {
        console.error(err);
      }
    } else {
      res.status(200).send(payload);
    }
  }),
);

/**
 *  @swagger
 *  /api/projects/count:
 *    get:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Count all projects
 *      description: Count all projects
 *      responses:
 *        200:
 *          description: Projects count successfully received
 *          content:
 *            application/json:
 *              schema:
 *                type: array
 *                items:
 *                  $ref: "#/components/schemas/Projects"
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Data not found
 *        500:
 *          description: Some server error
 */
router.get(
  '/count',
  wrapAsync(async (req, res) => {
    const currentUser = req.currentUser;
    const runtimeContext = req.runtimeContext;
    const payload = await ProjectsDBApi.findAll(req.query, {
      countOnly: true,
      currentUser,
      runtimeContext,
    });

    res.status(200).send(payload);
  }),
);

/**
 *  @swagger
 *  /api/projects/autocomplete:
 *    get:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Find all projects that match search criteria
 *      description: Find all projects that match search criteria
 *      responses:
 *        200:
 *          description: Projects list successfully received
 *          content:
 *            application/json:
 *              schema:
 *                type: array
 *                items:
 *                  $ref: "#/components/schemas/Projects"
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Data not found
 *        500:
 *          description: Some server error
 */
router.get('/autocomplete', async (req, res) => {
  const payload = await ProjectsDBApi.findAllAutocomplete(
    req.query.query,
    req.query.limit,
    req.query.offset,
  );

  res.status(200).send(payload);
});

/**
 * @swagger
 *  /api/projects/{id}:
 *    get:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Get selected item
 *      description: Get selected item
 *      parameters:
 *        - in: path
 *          name: id
 *          description: ID of item to get
 *          required: true
 *          schema:
 *            type: string
 *      responses:
 *        200:
 *          description: Selected item successfully received
 *          content:
 *            application/json:
 *              schema:
 *                $ref: "#/components/schemas/Projects"
 *        400:
 *          description: Invalid ID supplied
 *        401:
 *          $ref: "#/components/responses/UnauthorizedError"
 *        404:
 *          description: Item not found
 *        500:
 *          description: Some server error
 */
router.get(
  '/:id',
  wrapAsync(async (req, res) => {
    if (!isUuidV4(req.params.id)) {
      return res.status(400).send('Invalid project id');
    }

    const runtimeContext = req.runtimeContext;
    const payload = await ProjectsDBApi.findBy(
      { id: req.params.id },
      { runtimeContext },
    );

    res.status(200).send(payload);
  }),
);

/**
 * @swagger
 *  /api/projects/{id}/offline-manifest:
 *    get:
 *      security:
 *        - bearerAuth: []
 *      tags: [Projects]
 *      summary: Get offline manifest for PWA download
 *      description: Returns a manifest of all assets needed to use the project offline
 *      parameters:
 *        - in: path
 *          name: id
 *          description: Project ID
 *          required: true
 *          schema:
 *            type: string
 *        - in: query
 *          name: variant
 *          description: Device type for variant selection (mobile or desktop)
 *          schema:
 *            type: string
 *            enum: [mobile, desktop]
 *            default: desktop
 *      responses:
 *        200:
 *          description: Offline manifest successfully generated
 *        400:
 *          description: Invalid project ID
 *        404:
 *          description: Project not found
 *        500:
 *          description: Server error
 */
router.get(
  '/:id/offline-manifest',
  wrapAsync(async (req, res) => {
    if (!isUuidV4(req.params.id)) {
      return res.status(400).send('Invalid project id');
    }

    const PWAManifestService = require('../services/pwa_manifest');
    const { variant = 'desktop' } = req.query;

    const manifest = await PWAManifestService.generateManifest(
      req.params.id,
      variant,
    );

    res.status(200).json(manifest);
  }),
);

router.use('/', require('../helpers').commonErrorHandler);

module.exports = router;
