import Env from "@ioc:Adonis/Core/Env";
import type { HttpContextContract } from "@ioc:Adonis/Core/HttpContext";
import Users from "App/Models/Users";
import jwt from "jsonwebtoken";
import { schema, rules } from "@ioc:Adonis/Core/Validator";
export default class UsersController {
  public async index({}: HttpContextContract) {}

  public async create({ request, response }: HttpContextContract) {
    try {
      if ((await Users.findBy("username", request.all().username)) === null) {
        const userSchema = schema.create({
          username: schema.string({ trim: true }, [
            rules.unique({
              table: "users",
              column: "username",
              caseInsensitive: true,
            }),
          ]),
          password: schema.string({}, [rules.minLength(8)]),
        });

        const data = await request.validate({ schema: userSchema });
        const user = await Users.create(data);

        return response.status(201).send({ mess: "REGISTER_SUCCESS" });
      } else {
        return response.status(203).send({ mess: "USERNAME EXIST" });
      }
    } catch (error) {
      response.status(500).send({ mess: "CREATE USER FAIL", error: error });
    }
  }

  public async checkLogin({ request, response, auth }: HttpContextContract) {
    const { username, password } = request.all();
    try {
      const userLogin = await Users.findBy("username", username);
      if (userLogin !== null) {
        const user = await auth.attempt(username, password);
        delete user.$original.password;
        const accessToken = jwt.sign(user.$original, Env.get("JWT_KEY"), {
          expiresIn: "365d",
        });
        await auth.login(user);
        return response
          .status(200)
          .send({ mess: "AUTHENTICATION_SUCCESS", accessToken: accessToken });
      } else {
        return response.status(204).send("USER NOT EXISTS");
      }
    } catch (error) {
      console.log(error);
      response.status(500).send({ mess: "LOGIN FAIL", error: error });
    }
  }

  public async show({}: HttpContextContract) {}

  public async edit({}: HttpContextContract) {}

  public async update({}: HttpContextContract) {}

  public async destroy({}: HttpContextContract) {}
}
