import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
// import User from 'App/Models/User';
// import Dataset from 'App/Models/Dataset';
// import License from 'App/Models/License';
// import Project from 'App/Models/Project';
// import Title from 'App/Models/Title';
// import Description from 'App/Models/Description';
// import Language from 'App/Models/Language';
// import Coverage from 'App/Models/Coverage';
// import Collection from 'App/Models/Collection';
// import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
// import dayjs from 'dayjs';
import Person from 'App/Models/Person';

import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';

export default class PersonController {
    public async index({ auth, request, inertia }: HttpContextContract) {
        // const user = (await User.find(auth.user?.id)) as User;
        const page = request.input('page', 1);
        let persons: ModelQueryBuilderContract<typeof Person, Person> = Person.query();

        // if (request.input('search')) {
        //     // users = users.whereRaw('name like %?%', [request.input('search')])
        //     const searchTerm = request.input('search');
        //     datasets.where('name', 'ilike', `%${searchTerm}%`);
        // }

        if (request.input('sort')) {
            type SortOrder = 'asc' | 'desc' | undefined;
            let attribute = request.input('sort');
            let sortOrder: SortOrder = 'asc';

            if (attribute.substr(0, 1) === '-') {
                sortOrder = 'desc';
                // attribute = substr(attribute, 1);
                attribute = attribute.substr(1);
            }
            persons.orderBy(attribute, sortOrder);
        } else {
            // users.orderBy('created_at', 'desc');
            persons.orderBy('id', 'asc');
        }

        // const results = await Database
        // .query()
        // .select(Database.raw("CONCAT('https://doi.org/', b.value) AS concatenated_value"))
        // .from('documents as doc')
        // .innerJoin('dataset_identifiers as b', 'doc.id', 'b.dataset_id')
        // .groupBy('a.id').toQuery();

        // const users = await User.query().orderBy('login').paginate(page, limit);
        const myPersons = await persons
            // .where('account_id', user.id)
            // .preload('titles')
            // .preload('user', (query) => query.select('id', 'login'))
            .paginate(page, 10);

        return inertia.render('Submitter/Person/Index', {
            // testing: 'this is a test',
            persons: myPersons.serialize(),
            filters: request.all(),
            can: {
                // create: await auth.user?.can(['dataset-submit']),
                edit: await auth.user?.can(['dataset-edit']),
                delete: await auth.user?.can(['dataset-delete']),
            },
        });
    }
}
