"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAccess = exports.getAccesses = exports.registerAccess = void 0;
const express_validator_1 = require("express-validator");
const pagination_1 = require("../../util/pagination");
const aws_1 = require("../../services/aws");
const validate_url_1 = __importDefault(require("../../util/validate-url"));
const prisma_1 = require("../../database/prisma");
const registerAccess = async (req, res, next) => {
    try {
        let { userId, page, country, city, lat, lon, isp, timezone, ip, device, state, road, formatted, } = req.body;
        const errors = (0, express_validator_1.validationResult)(req);
        // const ip = req.ip || req.socket.remoteAddress;
        if (!errors.isEmpty()) {
            const error = new Error(errors.array()[0].msg);
            error.statusCode = 422;
            throw error;
        }
        const accessData = {
            country,
            city,
            isp,
            timezone,
            device,
            page,
            state,
            road,
            formatted,
            ip,
        };
        if (Boolean(userId)) {
            const user = await prisma_1.prisma.user.findUnique({
                where: { id: Number(userId) },
                include: { dadosPessoais: true },
            });
            if (!user) {
                const error = new Error('Utilizador não encontrado!');
                error.statusCode = 422;
                throw error;
            }
            accessData.userId = Number(userId);
        }
        if (lat) {
            accessData.lat = Number(lat);
        }
        if (lon) {
            accessData.lon = Number(lon);
        }
        const access = await prisma_1.prisma.access.create({ data: accessData });
        res.status(201).json({ msg: 'Cadastrado', access });
    }
    catch (err) {
        next(err);
    }
};
exports.registerAccess = registerAccess;
// Funcao Para pegar todos os accesss
const getAccesses = async (req, res, next) => {
    var _a, _b, _c, _d;
    try {
        const { userId, country, city, device, operator, pageVisited } = req.query;
        const filterObj = {};
        const page = (0, pagination_1.getPage)(req.query.page);
        let paramPerPage = req.query.perPage;
        let perPage = 50;
        if (paramPerPage) {
            perPage = +paramPerPage;
        }
        if (Boolean(userId)) {
            filterObj.userId = Number(userId);
        }
        if (Boolean(country)) {
            filterObj.country = country;
        }
        if (Boolean(city)) {
            filterObj.city = city;
        }
        if (Boolean(device)) {
            filterObj.device = device;
        }
        if (Boolean(operator)) {
            filterObj.operator = operator;
        }
        if (Boolean(pageVisited)) {
            filterObj.page = pageVisited;
        }
        const total = await prisma_1.prisma.access.count({ where: filterObj });
        const accesses = await prisma_1.prisma.access.findMany({
            where: filterObj,
            take: perPage,
            skip: (0, pagination_1.skip)(page, perPage),
            orderBy: { createdAt: 'desc' },
            include: { user: { include: { dadosPessoais: true } } },
        });
        for (let access of accesses) {
            if (((_b = (_a = access === null || access === void 0 ? void 0 : access.user) === null || _a === void 0 ? void 0 : _a.dadosPessoais) === null || _b === void 0 ? void 0 : _b.fotoURL) &&
                !(0, validate_url_1.default)((_d = (_c = access === null || access === void 0 ? void 0 : access.user) === null || _c === void 0 ? void 0 : _c.dadosPessoais) === null || _d === void 0 ? void 0 : _d.fotoURL)) {
                access.user.dadosPessoais.fotoURL = await (0, aws_1.getURL)(access.user.dadosPessoais.fotoURL);
            }
        }
        res.status(200).json({
            msg: 'Sucesso',
            accesses,
            ...(0, pagination_1.paginationResult)(total, page, perPage),
        });
    }
    catch (err) {
        next(err);
    }
};
exports.getAccesses = getAccesses;
// Funcao que pega uma unico access
const getAccess = async (req, res, next) => {
    var _a, _b;
    try {
        const { id } = req.params;
        const access = await prisma_1.prisma.access.findUnique({
            where: { id: Number(id) },
            include: { user: { include: { dadosPessoais: true } } },
        });
        if (!access) {
            const error = new Error('Access não encontrado!');
            error.statusCode = 422;
            throw error;
        }
        if ((_b = (_a = access === null || access === void 0 ? void 0 : access.user) === null || _a === void 0 ? void 0 : _a.dadosPessoais) === null || _b === void 0 ? void 0 : _b.fotoURL) {
            access.user.dadosPessoais.fotoURL = await (0, aws_1.getURL)(access.user.dadosPessoais.fotoURL);
        }
        res.status(200).json({ msg: 'Sucesso', access });
    }
    catch (err) {
        next(err);
    }
};
exports.getAccess = getAccess;
