const { resSukses, resError } = require("../../payload/payload.js");

const {
    allAddress,
    byIdAddress,
    createAddress,
    updateAddress,
    deleteAddress
} = require("./service.js");


const semuaAlamat = async (req, res) => {
    try {
        const data = await allAddress();
        return resSukses(res, 200, "success", "Data alamat", data);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

const AlamatId = async (req, res) => {
    try {
        const { id } = req.params;

        const data = await byIdAddress(id);

        if (!data) {
            return resError(res, 404, "error", "Data alamat tidak ditemukan", null);
        }

        return resSukses(res, 200, "success", "Detail alamat", data);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};


const buatAlamat = async (req, res) => {
    try {
        const { nama_penerima, no_hp, alamat , kode_post, kota } = req.body;
        const user_id = req.user.id;

        const body = {
            nama_penerima,
            no_hp,
            alamat, 
            kode_post, 
            kota,
            user_id
        };
        const result = await createAddress(body);

        return resSukses(res, 201, "success", "Alamat berhasil ditambahkan", result);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};


const editAlamat = async (req, res) => {
    try {
        const { id } = req.params;
        const { nama_penerima, no_hp, alamat , kode_post, kota} = req.body;
        const user_id = req.user.id;

        const data = await byIdAddress(id);

        if (!data) {
            return resError(res, 404, "error", "Data alamat tidak ditemukan", null);
        }

        const body = {
            nama_penerima,
            no_hp,
            alamat, 
            kode_post, 
            kota,
            user_id
        };

        const result = await updateAddress(id, body);

        return resSukses(res, 200, "success", "Data alamat berhasil diupdate", result);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};


const hapusAlamat = async (req, res) => {
    try {
        const { id } = req.params;

        const data = await byIdAddress(id);

        if (!data) {
            return resError(res, 404, "error", "Data alamat tidak ditemukan", null);
        }

        await deleteAddress(id);

        return resSukses(res, 200, "success", "Data alamat berhasil dihapus", null);
    } catch (error) {
        return resError(res, 500, "error", error.message);
    }
};

module.exports = {
    semuaAlamat,
    AlamatId,
    buatAlamat,
    editAlamat,
    hapusAlamat
};