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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
import express, { Router } from "express";
import serverless from "serverless-http";
import Redis from "ioredis";
import { initClient } from './utils.js';
import { errorHandler, setJioCopilotSessionCookie } from './middleware.js';
import swaggerJSDoc from 'swagger-jsdoc';
import yaml from 'js-yaml'
import fs from 'fs';
import { RedisListCache } from './cache.js';
import {
    getApplications,
    createApplication,
    getLocations,
    createLocation,
    updateLocation,
    getBrands,
    createBrand,
    updateBrand,
    createProduct,
    createInventory,
    getCompanyCreds,
    createUpdateCompanyCreds
} from './functions.js'
import OpenAI from 'openai';
import compression from 'compression';
import cookieParser from 'cookie-parser';
const listCache = new RedisListCache({ namespace: "fc" })
const redis = new Redis({
    host: 'redis-12291.c305.ap-south-1-1.ec2.cloud.redislabs.com',
    port: 12291,
    password: 'KQCVapXXF2ioM4zF5krQFImzAYkKWY5l',
    username: "default"
});
const skills = {
    getApplications,
    createApplication,
    getLocations,
    createLocation,
    updateLocation,
    getBrands,
    createBrand,
    updateBrand,
    createProduct,
    createInventory,
    getCompanyCreds,
    createUpdateCompanyCreds
}
const app = express();
const router = Router();
api.use("/api/", router);
const port = process.env.PORT;
app.use(express.json({}));
const swaggerDefinition = {
    openapi: '3.0.0',
    info: {
        title: 'Express API Documentation',
        version: '1.0.0',
        description: 'This is the API documentation for my Express application.'
    },
    servers: [{
        url: "https://934a-45-119-30-178.ngrok-free.app"
    }]
};
const options = {
    swaggerDefinition,
    // Path to the API docs
    apis: ['./index.js'], // Adjust the path according to your file structure
};
app.use(compression())
app.use(cookieParser())

/**
 * @swagger
 * components:
 *   schemas:
 *     CompanyCreds:
 *       type: object
 *       properties:
 *         clientId:
 *           type: string
 *           description: Client ID for the company
 *         clientSecret:
 *           type: string
 *           description: Client secret for the company
 *       required:
 *          - clientId
 *          - clientSecret
 *     CreateUpdateLocation:   
 *       type: object
 *       required:
 *         - code
 *         - name
 *         - gst
 *         - manager
 *         - address
 *       properties:
 *         code:
 *           type: string
 *           description: Unique code for the location
 *         name:
 *           type: string
 *           description: Name of the location
 *         gst:
 *           type: object
 *           required:
 *             - legal_name
 *             - value
 *           properties:
 *             legal_name:
 *               type: string
 *               description: Legal name for GST purposes
 *             value:
 *               type: string
 *               description: GST value
 *         manager:
 *           type: object
 *           required:
 *             - manager_name
 *             - email
 *             - number
 *             - country_code
 *           properties:
 *             manager_name:
 *               type: string
 *               description: Name of the manager
 *             email:
 *               type: string
 *               description: Email of the manager
 *             number:
 *               type: string
 *               description: Contact number of the manager
 *             country_code:
 *               type: string
 *               description: Country code for the manager's contact number
 *         address:
 *           type: object
 *           required:
 *             - address1
 *             - country
 *             - pincode
 *             - city
 *             - state
 *           properties:
 *             address1:
 *               type: string
 *               description: Primary address line
 *             address2:
 *               type: string
 *               description: Secondary address line
 *             country:
 *               type: string
 *               description: Country of the location
 *             pincode:
 *               type: string
 *               description: Postal code of the location
 *             city:
 *               type: string
 *               description: City of the location
 *             state:
 *               type: string
 *               description: State of the location
 *             latitude:
 *               type: number
 *               description: Latitude for the location
 *             longitude:
 *               type: number
 *               description: Longitude for the location
 *             landmark:
 *               type: string
 *               description: Landmark near the location
 *     Brand:
 *       type: object
 *       properties:
 *         name:
 *           type: string
 *         logo:
 *           type: string
 *         id:
 *           type: string
 *     BrandCreation:
 *       type: object
 *       required:
 *         - name
 *         - logo
 *         - description
 *       properties:
 *         name:
 *           type: string
 *         logo:
 *           type: string
 *         description:
 *           type: string
 *     ErrorResponse:
 *       type: object
 *       properties:
 *         message:
 *           type: string
 *           description: Error message
 */

router.get(['/swagger.yaml', '/swagger.json'], (req, res) => {
    // Initialize swagger-jsdoc
    const swaggerSpec = swaggerJSDoc(options);

    // Convert to YAML
    const swaggerYAML = yaml.dump(swaggerSpec);
    switch (req.path.split('.').pop()) {
        case 'json':
            res.setHeader('Content-Type', 'application/json');
            return res.send(JSON.stringify(swaggerSpec, null, 2));
        case 'yaml':
            res.setHeader('Content-Type', 'text/yaml');
            return res.send(swaggerYAML);
    }
});

/**
 * @swagger
 * /_healthz:
 *   get:
 *     operationId: getHealthZ
 *     description: Check server health
 *     responses:
 *       200:
 *         description: Server is healthy
 *         content:
 *           text/plain:
 *             schema:
 *               type: string
 *               example: Hello World!
 */
router.get("/_healthz", (req, res) => {
    res.send('Hello World!');
});
router.get("/privacy", (req, res) => {
    res.send('This is the privacy policy page!');
});

/**
 * @swagger
 * /company/{companyId}:
 *   get:
 *     operationId: getOrVerifyCompanyCredentials
 *     description: Retrieve company credentials
 *     tags: [Company]
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The company ID
 *     responses:
 *       200:
 *         description: Company credentials retrieved successfully
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/CompanyCreds'
 *       404:
 *         description: Company credentials not found
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get("/company/:companyId", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const creds = await redis.get(`${companyId}:creds`);
        if (!creds) {
            throw {
                message: "company creds not found"
            }
        }
        res.json({ ...JSON.parse(creds), companyId })
    } catch (e) {
        next(e)
    }
})

/**
 * @swagger
 * /company/{companyId}:
 *   put:
 *     operationId: updateCompanyCredentials
 *     description: Update company credentials
 *     tags: [Company]
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The company ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/CompanyCreds'
 *     responses:
 *       200:
 *         description: Company credentials updated successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *       400:
 *         description: Invalid input
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.put("/company/:companyId", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const { clientId, clientSecret } = req.body
        const creds = await redis.set(`${companyId}:creds`, JSON.stringify({ clientId, clientSecret }));
        res.json({ message: "company creds saved" })
    } catch (e) {
        next(e)
    }
})



/**
 * @swagger
 * /company/{companyId}/applications:
 *   get:
 *     operationId: getSalesChannelByCompany
 *     description: Retrieve applications for a specific company
 *     tags: [Company]
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The ID of the company to retrieve applications for
 *     responses:
 *       200:
 *         description: List of applications for the specified company
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   name:
 *                     type: string
 *                     description: Name of the application
 *                   id:
 *                     type: string
 *                     description: ID of the application
 *                   token:
 *                     type: string
 *                     description: Token associated with the application
 *                   domain:
 *                     type: string
 *                     description: Primary domain of the application
 *                   logo:
 *                     type: string
 *                     description: Logo URL of the application
 *       500:
 *         description: Server error
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get("/company/:companyId/applications", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const client = await initClient(companyId);
        let applications = await client.configuration.getApplications({ pageSize: 100 });
        applications = applications.items.map(i => {
            return {
                name: i.name,
                id: i.id,
                token: i.token,
                domain: i.domains?.find(i => i.is_primary)?.name,
                logo: i.logo?.secure_url
            }
        })
        res.json(applications)
    } catch (e) {
        next(e)
    }
})

/**
 * @swagger
 * /company/{companyId}/brands:
 *   get:
 *     summary: Retrieves a list of brands for a specific company
 *     tags: [Brands]
 *     operationId: getCompanyBrands
 *     description: Fetches a list of brands associated with the given company ID.
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The unique identifier of the company
 *     responses:
 *       200:
 *         description: A list of brands
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/Brand'
 */
router.get("/company/:companyId/brands", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const client = await initClient(companyId);
        let brands = await client.companyProfile.getBrands({ pageSize: 300 });
        brands = brands.items.map(i => {
            return {
                name: i?.brand?.name,
                logo: i?.brand?.logo,
                id: i?.brand?.uid,
            }
        })
        res.json(brands)
    } catch (e) {
        next(e)
    }
})

/**
 * @swagger
 * /company/{companyId}/brands:
 *   post:
 *     summary: Creates a new brand for a specific company
 *     tags: [Brands]
 *     operationId: createCompanyBrand
 *     description: Adds a new brand to the company profile.
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The unique identifier of the company
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/BrandCreation'
 *     responses:
 *       200:
 *         description: Brand created successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 id:
 *                   type: string
 * 
 * /company/{companyId}/brands/{brandId}:
 *   put:
 *     summary: Creates a new brand for a specific company
 *     tags: [Brands]
 *     operationId: updateCompanyBrand
 *     description: updated an existing brand.
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The unique identifier of the company
 *       - in: path
 *         name: brandId
 *         required: true
 *         schema:
 *           type: number
 *         description: The unique identifier of the brand
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/BrandCreation'
 *     responses:
 *       200:
 *         description: Brand updated successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 id:
 *                   type: string
 */
router.post("/company/:companyId/brands", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const client = await initClient(companyId);
        const {
            name,
            logo = "https://cdn.pixelbin.io/v2/falling-surf-7c8bb8/fyprod/wrkr/platform/pictures/favicon/original/ZWTmgEoFQ-platform-favicon.png",
            description
        } = req.body
        let brands = await client.companyProfile.createBrand({
            body: {
                name,
                description,
                logo,
                banner: { portrait: logo, landscape: logo }
            }
        });
        res.json({ message: "brand created", id: brands?.uid })
    } catch (e) {
        next(e)
    }
})
router.put("/company/:companyId/brands/:brandId", async (req, res, next) => {
    try {
        const { companyId, brandId } = req.params;
        const client = await initClient(companyId);
        const {
            name,
            logo = "https://cdn.pixelbin.io/v2/falling-surf-7c8bb8/fyprod/wrkr/platform/pictures/favicon/original/ZWTmgEoFQ-platform-favicon.png",
            description
        } = req.body
        let brands = await client.companyProfile.editBrand({
            brandId,
            body: {
                name,
                description,
                logo,
                banner: { portrait: logo, landscape: logo }
            }
        });
        res.json({ message: "brand updated", id: brands?.id })
    } catch (e) {
        next(e)
    }
})

/**
 * @swagger
 * /company/{companyId}/locations:
 *   get:
 *     operationId: getLocationsByCompany
 *     description: get all company locations
 *     tags: [Company]
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The ID of the company to add a location for
 *     responses:
 *       200:
 *         description: location list
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 properties:
 *                   id:
 *                     type: number
 *                     description: Location id
 *                   code:
 *                     type: string
 *                     description: Location code
 *                   name:
 *                     type: string
 *                     description: Location code
 *                   documents:
 *                     type: array
 *                     description: Location gst documents
 *                     items:
 *                       type: object
 *                       properties:
 *                         type:
 *                           type: string
 *                           description: document type
 *                         value:
 *                           type: string
 *                           description: document number
 *                         verified:
 *                           type: boolean
 *                           description: document number verification status
 *                         legal_name:
 *                           type: boolean
 *                           description: document owner
 *       400:
 *         description: Invalid input
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.get("/company/:companyId/locations", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const client = await initClient(companyId.toString());
        let locations = await client.companyProfile.getLocations({ pageSize: 100 });
        locations = locations.items.map(i => {
            return {
                name: i.name,
                id: i.uid,
                code: i.code,
                documents: i.documents
            }
        })
        res.json(locations)
    } catch (e) {
        next(e)
    }
})
/**
 * @swagger
 * /company/{companyId}/locations:
 *   post:
 *     operationId: createLocationsForCompany
 *     description: Add a new location for a specific company
 *     tags: [Company]
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The ID of the company to add a location for
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema: 
 *             $ref: '#/components/schemas/CreateUpdateLocation'
 *     responses:
 *       200:
 *         description: Location created successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 id:
 *                   type: string
 *                   description: Location id
 *       400:
 *         description: Invalid input
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 * /company/{companyId}/locations/{locationId}:
 *   put:
 *     operationId: updateLocationByCompany
 *     description: update a location for a specific company
 *     tags: [Company]
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The ID of the company to add a location for
 *       - in: path
 *         name: locationId
 *         required: true
 *         schema:
 *           type: string
 *         description: The ID of the location to be updated
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema: 
 *             $ref: '#/components/schemas/CreateUpdateLocation'
 *     responses:
 *       200:
 *         description: Location updated successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 id:
 *                   type: string
 *                   description: Location id
 *       400:
 *         description: Invalid input
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ErrorResponse'
 */
router.post("/company/:companyId/locations", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const { code,
            name,
            gst: {
                legal_name,
                value
            },
            manager: {
                manager_name, email, number, country_code
            },
            address: {
                address1,
                address2,
                country,
                pincode,
                city,
                state,
                latitude = 19.2762702,
                longitude = 72.8929,
                landmark = ""
            },

        } = req.body
        const client = await initClient(companyId);
        let locations = await client.companyProfile.createLocation({
            body: {
                name,
                display_name: name,
                code,
                company: parseInt(companyId),
                documents: [{
                    type: "gst",
                    legal_name: legal_name,
                    value: value, verified: true
                }],
                address: {
                    "address1": address1,
                    "address2": address2,
                    "country": country,
                    "pincode": pincode,
                    "city": city,
                    "state": state,
                    "latitude": latitude,
                    "longitude": longitude,
                    "landmark": landmark
                },
                manager: {
                    "name": manager_name,
                    "email": email,
                    "mobile_no": {
                        "number": number,
                        "country_code": country_code
                    }
                },
                contact_numbers: [
                    {
                        "number": number,
                        "country_code": country_code
                    }
                ],
                store_type: "high_street"

            }
        });

        res.json({ message: "location added", id: locations?.uid })
    } catch (e) {
        next(e)
    }
})
router.put("/company/:companyId/locations/locationId", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const { code,
            name,
            gst: {
                legal_name,
                value
            },
            manager: {
                manager_name, email, number, country_code
            },
            address: {
                address1,
                address2,
                country,
                pincode,
                city,
                state,
                latitude = 19.2762702,
                longitude = 72.8929,
                landmark = ""
            },

        } = req.body
        const client = await initClient(companyId);
        let locations = await client.companyProfile.createLocation({
            body: {
                name,
                display_name: name,
                code,
                company: parseInt(companyId),
                documents: [{
                    type: "gst",
                    legal_name: legal_name,
                    value: value, verified: true
                }],
                address: {
                    "address1": address1,
                    "address2": address2,
                    "country": country,
                    "pincode": pincode,
                    "city": city,
                    "state": state,
                    "latitude": latitude,
                    "longitude": longitude,
                    "landmark": landmark
                },
                manager: {
                    "name": manager_name,
                    "email": email,
                    "mobile_no": {
                        "number": number,
                        "country_code": country_code
                    }
                },
                contact_numbers: [
                    {
                        "number": number,
                        "country_code": country_code
                    }
                ],
                store_type: "high_street"

            }
        });

        res.json({ message: "location updated", id: locations?.id })
    } catch (e) {
        next(e)
    }
})



/**
 * @swagger
 * /company/{companyId}/products:
 *   post:
 *     summary: Creates a new product for a given company.
 *     description: This endpoint creates a new product with various attributes including name, slug, pricing, and more.
 *     operationId: createProduct
 *     tags:
 *       - Products
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: Unique identifier of the company.
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - name
 *               - slug
 *               - seller_identifier
 *               - brand_id
 *             properties:
 *               name:
 *                 type: string
 *                 description: Name of the product.
 *               slug:
 *                 type: string
 *                 description: URL-friendly identifier for the product.
 *               seller_identifier:
 *                 type: string
 *                 description: Unique identifier for the seller.
 *               brand_id:
 *                 type: string
 *                 description: Unique identifier for the brand.
 *               location_id:
 *                 type: string
 *                 description: Location identifier for the product.
 *               mrp:
 *                 type: number
 *                 default: 999
 *                 description: Maximum retail price of the product.
 *               selling_price:
 *                 type: number
 *                 default: 499
 *                 description: Selling price of the product.
 *     responses:
 *       200:
 *         description: Successful creation of the product.
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 id:
 *                   type: string
 *                 seller_identifier:
 *                   type: string
 */

router.post("/company/:companyId/products", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const { name,
            slug,
            seller_identifier,
            brand_id, location_id, mrp = 999, selling_price = 499
        } = req.body;
        const obj = {
            "name": name,
            "slug": slug,
            "brand_uid": brand_id,
            "item_code": seller_identifier,
            "teaser_tag": {},
            "net_quantity": {},
            "tax_identifier": {
                "reporting_hsn": "1202355241H1",
                "hsn_code": "1202355241",
                "hsn_code_id": "65769883ba99dcf407a2b1ed"
            },
            "country_of_origin": "India",
            "variants": {},
            "variant_media": {},
            "description": "PHA+WW91ciBwcm9kdWN0IGRlc2NyaXB0aW9uPC9wPg==",
            "short_description": "Your product description",
            "highlights": [],
            "company_id": 10,
            "template_tag": "c2-0-template",
            "currency": "INR",
            "media": [],
            "is_set": false,
            "sizes": [
                {
                    "size": "OS",
                    "price": mrp,
                    "price_effective": selling_price,
                    "price_transfer": 0,
                    "currency": "INR",
                    "item_length": 1,
                    "item_width": 1,
                    "item_height": 1,
                    "item_weight": 1,
                    "item_dimensions_unit_of_measure": "cm",
                    "item_weight_unit_of_measure": "gram",
                    "track_inventory": true,
                    "identifiers": [
                        {
                            "gtin_value": seller_identifier,
                            "gtin_type": "ean",
                            "primary": true
                        }
                    ],
                    "_custom_json": {},
                    "name": "OS"
                }
            ],
            "_custom_json": {},
            "size_guide": "",
            "product_group_tag": [],
            "product_publish": {
                "product_online_date": "2023-12-11T08:38:10.082Z",
                "is_set": false
            },
            "is_active": true,
            "custom_order": {
                "is_custom_order": false,
                "manufacturing_time": 0,
                "manufacturing_time_unit": "hours"
            },
            "multi_size": false,
            "no_of_boxes": 1,
            "is_dependent": false,
            "item_type": "digital",
            "tags": [],
            "departments": [
                19771
            ],
            return_config: {
                "returnable": false
            },
            "category_slug": "c2-0-cat",
            "trader": [
                {
                    "type": "Manufacturer",
                    "name": "Manufacturer",
                    "address": [
                        "Manufacturer Address"
                    ]
                }
            ],
            "return_config": {
                "returnable": true,
                time: 3,
                unit: "days"
            }
        }
        const client = await initClient(companyId);
        let product = await client.catalog.createProduct({
            body: obj
        });
        product = await client.catalog.getProduct({
            itemId: product.uid
        });
        res.json({
            message: "product created",
            id: product.data.uid,
            seller_identifier: product?.data?.sizes?.[0]?.seller_identifier
        });
    } catch (e) { next(e) }
})

/**
 * @swagger
 * /company/{companyId}/products/{productId}/inventory:
 *   post:
 *     summary: Updates inventory for a specific product.
 *     description: This endpoint updates the inventory details for a given product, including location, pricing, and quantity.
 *     operationId: updateInventory
 *     tags:
 *       - Inventory
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: Unique identifier of the company.
 *       - in: path
 *         name: productId
 *         required: true
 *         schema:
 *           type: string
 *         description: Unique identifier of the product.
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - location_id
 *               - seller_identifier
 *             properties:
 *               location_id:
 *                 type: string
 *                 description: Location identifier where the inventory is stored.
 *               mrp:
 *                 type: number
 *                 default: 999
 *                 description: Maximum retail price of the product.
 *               selling_price:
 *                 type: number
 *                 default: 499
 *                 description: Selling price of the product.
 *               seller_identifier:
 *                 type: string
 *                 description: Unique identifier for the seller.
 *     responses:
 *       200:
 *         description: Successful update of inventory.
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 */
router.post("/company/:companyId/products/:productId/inventory", async (req, res, next) => {
    try {
        const { companyId, productId } = req.params;
        const { location_id, mrp = 999, selling_price = 499, id, seller_identifier } = req.body;
        const client = await initClient(companyId);
        let product = await client.catalog.getProduct({
            itemId: productId
        });
        let inv = await client.catalog.updateRealtimeInventory({
            itemId: product.data.uid,
            sellerIdentifier: seller_identifier,
            body: {
                company_id: companyId,
                payload: [{
                    "seller_identifier": seller_identifier,
                    "store_id": location_id,
                    "price_marked": mrp,
                    "price_effective": selling_price,
                    "total_quantity": 10,
                    "tags": []
                }]
            }
        })

        res.json({ message: "inv created" });
    } catch (e) { next(e) }
})


/**
 * @swagger
 * /company/{companyId}/sales_channel:
 *   post:
 *     operationId: addSalesChannel
 *     summary: Create a sales channel for a given company
 *     description: This endpoint creates a new sales channel for the specified company.
 *     tags:
 *       - Sales Channel
 *     parameters:
 *       - in: path
 *         name: companyId
 *         required: true
 *         schema:
 *           type: string
 *         description: The ID of the company
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               brand_ids:
 *                 type: array
 *                 items:
 *                   type: integer
 *                 description: Array of brand IDs to be associated with the sales channel
 *               name:
 *                 type: string
 *                 description: Name of the sales channel
 *               subdomain:
 *                 type: string
 *                 description: subdomain associated with the sales channel
 *     responses:
 *       200:
 *         description: Sales channel successfully created
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                 app:
 *                   type: object
 *                   description: Details of the created sales channel
 *       400:
 *         description: Bad request
 *       500:
 *         description: Internal server error
 */

app.post("/company/:companyId/sales_channel", async (req, res, next) => {
    try {
        const { companyId } = req.params;
        const { brand_ids, name, subdomain } = req.body;
        const client = await initClient(companyId);

        let app = await client.configuration.createApplication({
            body: {
                "app": {
                    "company_id": (1).toString(),
                    "channel_type": "website-and-mobile-apps",
                    "auth": {
                        "enabled": true
                    },
                    "name": name,
                    "desc": "",
                    "mode": "live"
                },
                "configuration": {
                    "inventory": {
                        "brand": {
                            "criteria": "all",
                            "brands": []
                        },
                        "store": {
                            "criteria": "filter",
                            "rules": [
                                {
                                    "companies": [companyId],
                                    "brands": brand_ids
                                }
                            ],
                            "stores": []
                        },
                        "image": ["standard", "substandard", "default"],
                        "franchise_enabled": false,
                        "out_of_stock": true
                    },
                    "payment": {
                        "mode_of_payment": "ECOMM",
                        "source": "ECOMM"
                    },
                    "article_assignment": {
                        "post_order_reassignment": true,
                        "enforced_stores": [],
                        "rules": {
                            "store_priority": {
                                "enabled": false,
                                "storetype_order": []
                            }
                        }
                    }
                },
                "domain": {
                    "name": `${subdomain}.hostx5.de`
                }
            }
        })

        res.json({ message: "inv created", app });
    } catch (e) { next(e) }
})

const chatHtml = fs.readFileSync('./chat.html', 'utf-8');

app.get('/', async (req, res, next) => {
    try {
        res.send(chatHtml);
    } catch (error) {
        console.error(error);
        res.send('Something needs to be fixed!');
    }
});

app.get('/talk', async (req, res, next) => {
    try {
        res.send(chatHtml);
    } catch (error) {
        console.error(error);
        res.send('Something needs to be fixed!');
    }
});
app.get('/history', setJioCopilotSessionCookie, async (req, res) => {
    const session = req.jio_copilot_anonymous_session;
    let messages = [];
    if (session) {
        messages = await listCache.getAll(session);
    }
    messages = messages.filter(message => message.role === 'user' || message.role === 'assistant');
    res.json([{ role: 'assistant', content: 'Greetings! I\'m Jio Copilot, your digital aid for Jio platforms like TiraBeauty, JioCinema, JioMart, and JioFiber. Here to help with shopping, product exploration, content streaming, and internet/data plan navigation. How may I assist you today?' }, ...messages]);
});

app.delete('/history', setJioCopilotSessionCookie, async (req, res) => {
    const session = req.jio_copilot_anonymous_session;
    if (session) {
        await listCache.clear(session);
    }
    res.json({ success: true });
});

router.post(
    '/openai', setJioCopilotSessionCookie,
    async (req, res, next) => {
        const functions = [
            {
                "name": "getCompanyCreds",
                "description": "Retrieves credentials for a specific company based on its ID.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        }
                    },
                    "required": ["company_id"]
                }
            }, {
                "name": "createUpdateCompanyCreds",
                "description": "Creates or updates credentials for a company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "clientId": {
                            "type": "string",
                            "description": "Client ID for authentication."
                        },
                        "clientSecret": {
                            "type": "string",
                            "description": "Client secret for authentication."
                        }
                    },
                    "required": ["company_id", "clientId", "clientSecret"]
                }
            }, {
                "name": "getApplications",
                "description": "Retrieves a list of applications associated with a specific company ID.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        }
                    },
                    "required": ["company_id"]
                }
            }, {
                "name": "createBrand",
                "description": "Creates a new brand under a specific company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "name": {
                            "type": "string",
                            "description": "Name of the new brand."
                        },
                        "description": {
                            "type": "string",
                            "description": "Description of the new brand."
                        },
                        "logo": {
                            "type": "string",
                            "description": "URL of the brand's logo."
                        }
                    },
                    "required": ["company_id", "name", "description"]
                }
            }, {
                "name": "updateBrand",
                "description": "Updates the details of an existing brand within a company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "brand_id": {
                            "type": "string",
                            "description": "Unique identifier of the brand to be updated."
                        },
                        "name": {
                            "type": "string",
                            "description": "New name for the brand."
                        },
                        "description": {
                            "type": "string",
                            "description": "New description for the brand."
                        },
                        "logo": {
                            "type": "string",
                            "description": "New URL for the brand's logo."
                        },
                    },
                    "required": ["company_id", "brand_id", "name", "description"]
                }
            }, {
                "name": "getBrands",
                "description": "Retrieves a list of all brands associated with a specific company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company for which brands are being retrieved."
                        }
                    },
                    "required": ["company_id"]
                }
            }, {
                "name": "getLocations",
                "description": "Retrieves a list of all locations associated with a specific company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company for which locations are being retrieved."
                        }
                    },
                    "required": ["company_id"]
                }
            }, {
                "name": "createLocation",
                "description": "Creates a new location for a specified company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "name": {
                            "type": "string",
                            "description": "name of the location."
                        },
                        "code": {
                            "type": "string",
                            "description": "a unique code name."
                        },
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "address1": {
                            "type": "string",
                            "description": "Primary address line of the new location."
                        },
                        "address2": {
                            "type": "string",
                            "description": "Secondary address line of the new location."
                        },
                        "pincode": {
                            "type": "number",
                            "description": "Postal code of the new location."
                        },
                        "state": {
                            "type": "string",
                            "description": "State where the new location is situated."
                        },
                        "country": {
                            "type": "string",
                            "description": "State where the new location is situated."
                        },
                        "city": {
                            "type": "string",
                            "description": "City where the new location is situated."
                        },
                        "number": {
                            "type": "string",
                            "description": "Contact number for the new location. 10 digits"
                        },
                        "country_code": {
                            "type": "string",
                            "description": "Country code for the contact number eg 91"
                        },
                        "gst_name": {
                            "type": "string",
                            "description": "GST registered name associated with the new location."
                        },
                        "gst_no": {
                            "type": "string",
                            "description": "GST number associated with the new location."
                        },
                        "latitude": {
                            "type": "number",
                            "description": "Latitude coordinate for the new location."
                        },
                        "longitude": {
                            "type": "number",
                            "description": "Longitude coordinate for the new location."
                        },
                        "manager_name": {
                            "type": "string",
                            "description": "name of the store manager."
                        },
                        "email": {
                            "type": "string",
                            "description": "email of the store manager."
                        }
                    },
                    "required": ["company_id", "address1", "city", "state", 'country', "pincode", "gst_name", "gst_no", 'manager_name', 'email', 'code', 'country_code', 'number']
                }
            }, {
                "name": "updateLocation",
                "description": "update a existing location for a specified company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "location_id": {
                            "type": "number",
                            "description": "Unique identifier of the location."
                        },
                        "address1": {
                            "type": "string",
                            "description": "Primary address line of the new location."
                        },
                        "address2": {
                            "type": "string",
                            "description": "Secondary address line of the new location."
                        },
                        "pincode": {
                            "type": "string",
                            "description": "Postal code of the new location."
                        },
                        "state": {
                            "type": "string",
                            "description": "State where the new location is situated."
                        },
                        "city": {
                            "type": "string",
                            "description": "City where the new location is situated."
                        },
                        "number": {
                            "type": "string",
                            "description": "Contact number for the new location."
                        },
                        "country_code": {
                            "type": "string",
                            "description": "Country code for the contact number."
                        },
                        "gst_name": {
                            "type": "string",
                            "description": "GST registered name associated with the new location."
                        },
                        "gst_no": {
                            "type": "string",
                            "description": "GST number associated with the new location."
                        },
                        "latitude": {
                            "type": "number",
                            "description": "Latitude coordinate for the new location."
                        },
                        "longitude": {
                            "type": "number",
                            "description": "Longitude coordinate for the new location."
                        }
                    },
                    "required": ["company_id", 'brand_id', "address1", "city", "state", "pincode", "country_code", "gst_name", "gst_no"]
                }
            }, {
                "name": "createProduct",
                "description": "Creates a new product in the company's catalog.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "name": {
                            "type": "string",
                            "description": "Name of the new product."
                        },
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "slug": {
                            "type": "string",
                            "description": "SEO-friendly URL segment for the product."
                        },
                        "seller_identifier": {
                            "type": "string",
                            "description": "Unique identifier for the seller of the product."
                        },
                        "brand_id": {
                            "type": "number",
                            "description": "Unique identifier of the brand associated with the product."
                        },
                        "mrp": {
                            "type": "number",
                            "description": "Maximum Retail Price of the product."
                        },
                        "selling_price": {
                            "type": "number",
                            "description": "Selling price of the product."
                        }
                    },
                    "required": ["name", "company_id", "slug", "seller_identifier", "brand_id"]
                }
            }, {
                "name": "createInventory",
                "description": "Creates a new inventory record for a specific product in a company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "product_id": {
                            "type": "number",
                            "description": "Unique identifier of the product."
                        },
                        "seller_identifier": {
                            "type": "string",
                            "description": "Unique identifier for the seller of the product."
                        },
                        "location_id": {
                            "type": "number",
                            "description": "Unique identifier of the location where the inventory is stored."
                        },
                        "mrp": {
                            "type": "number",
                            "description": "Maximum Retail Price of the product."
                        },
                        "selling_price": {
                            "type": "number",
                            "description": "Selling price of the product."
                        }
                    },
                    "required": ["company_id", "product_id", "seller_identifier", "location_id"]
                }
            }, {
                "name": "createApplication",
                "description": "Creates a new application for a specified company.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "company_id": {
                            "type": "number",
                            "description": "Unique identifier of the company."
                        },
                        "brand_ids": {
                            "type": "array",
                            "description": "Array of brand IDs associated with the application.",
                            "items": {
                                "type": "number"
                            }
                        },
                        "name": {
                            "type": "string",
                            "description": "Name of the new application."
                        },
                        "subdomain": {
                            "type": "string",
                            "description": "Subdomain for the application's URL."
                        }
                    },
                    "required": ["company_id", "brand_ids", "name", "subdomain"]
                }
            }

        ];

        const messages = [{
            role: 'system',
            content: `you are an onboarding buddy chatbot for fynd platform, you help logged in userd who have access to a company to clear their salechannels/ websites, always start by asking the same. when asking questions from the use ask one at a time, ask user for one input at a time. You must initiate the conversation always. 

            NOTEs FOR YOU: 
            always check if you have the credentials for a company_id
            you always show the function name and the generated JSON args when functions are called
            platform domain is platfrom.fyndx5.de
            to get started yo need to get the companyId, clientId and secret from the user. always check if the credentials exist, if not save them
            to create a sales channel you require at least one brand. fetch and show the brands
            to create a product you need a brand. fetch and show the brand
            once the product is created it takes some time reflect in the db before the inventory is added
            for a product to be visible on your sales channel you must also add inventory for it
            stores, location, warehouses mean the same, 
            seller_identifier, item_code are unique indentifier of the product, both may be the same 
            assume seller_identifier is a string separated by _ and in all caps always.
            assume data if possible

            UI Links: always give the ui link when performing actions
            company credentials create link = https://platform.fyndx5.de/company/{companyId}/apis/oauthclient/create
            company homepage url = https://platform.fyndx5.de/company/{companyId}/home
            company profile url = https://platform.fyndx5.de/company/{companyId}/profile
            company location url = https://platform.fyndx5.de/company/{companyId}/profile/edit-store/{locationId}
            company brand url = https://platform.fyndx5.de/company/{companyId}/profile/edit-brand/{brandId}
            company sales channels url = https://platform.fyndx5.de/company/{companyId}/application/{applicationId}/products
            company product listing url= https://platform.fyndx5.de/company/{companyId}/products/list
            company product url = https://platform.fyndx5.de/company/{companyId}/products/{itemId}/edit.`
        }];
        const session = req.jio_copilot_anonymous_session;
        if (session) {
            messages.push(...(await listCache.getAll(session)));
        }

        const userMessage = { role: 'user', content: req.body.prompt };
        messages.push(userMessage);
        await listCache.setItems(session, userMessage);

        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Content-Type', 'text/event-stream');
        // res.setHeader('Access-Control-Allow-Origin', http://);
        res.setHeader('Connection', 'keep-alive');
        res.flushHeaders();

        try {
            await nextStep(session, messages, skills, functions, res);
            res.end();
        } catch (error) {
            if (error.code === 'context_length_exceeded') {
                res.write('You have exhausted the conversation limit, clear history and start again!');
                res.end();
            }
            res.write('There is some issue is going on. Please try again later.');
            res.end();
        }
    });

app.use("/api", router);
app.use(errorHandler)

app.listen(port, async () => {
    console.log(`Example app listening at http://localhost:${port}`);
    const swaggerSpec = swaggerJSDoc(options);

    // Convert to YAML
    const swaggerYAML = yaml.dump(swaggerSpec);
    await fs.writeFileSync("swagger.yaml", swaggerYAML, 'utf-8')
    await fs.writeFileSync("swagger.json", JSON.stringify(swaggerSpec, null, 2), 'utf-8')
});

async function nextStep(session, messages, skills, functions, res) {
    const conn = new OpenAI({ apiKey: "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" });
    const streamResponse = await conn
        .chat.completions.create({
            model: 'gpt-4',
            messages,
            functions,
            function_call: 'auto',
            temperature: 0.5,
            stream: true
        }).catch(async err => {
            console.error(err);
            const openAIError = new Error(err.error.message);
            openAIError.code = err.error.code;
            throw openAIError;
        });

    let finalMessage = '';
    const functionCall = { name: null, arguments: '' };

    for await (const line of streamResponse) {
        const choice = line.choices[0];
        if (choice.delta.function_call) {
            const fc = choice.delta.function_call;
            if (fc.name) {
                // res.write(`Detected Function: ${fc.name}\n\n`);
                // res.flush();
                functionCall.name = fc.name;
            }
            if (fc.arguments) {
                functionCall.arguments += fc.arguments;
            }
        } else if (!choice.finish_reason && choice.delta.content) {
            finalMessage += choice.delta.content;
            res.write(`${choice.delta.content}`);
            res.flush();
        }
    }

    if (!functionCall.name) {
        const assistantMessage = { role: 'assistant', content: finalMessage };
        messages.push(assistantMessage);
        await listCache.setItems(session, assistantMessage);
        return;
    }

    const functionName = functionCall.name;
    const args = JSON.parse(functionCall.arguments);
    if (!skills[functionName]) {
        throw new Error(`No skill implemented for this function: ${functionName}`);
    }

    // res.write(`Executing Function: ${functionName} with arguments ${JSON.stringify(args)} \n\n`);
    // res.flush();
    const skillRes = await skills[functionName]({ ...args, headers: { 'openai-ephemeral-user-id': session } }).catch(e => {
        return { message: e }
    });

    if (skillRes) {
        const functionMessage = { role: 'function', name: functionName, content: JSON.stringify(skillRes) };
        messages.push(functionMessage);
        await listCache.setItems(session, functionMessage);
    }
    return nextStep(session, messages, skills, functions, res);
}

export const handler = serverless(api);