1use clap::{Args, Parser, Subcommand, ValueEnum};
13use serde_json::json;
14use uuid::Uuid;
15
16use super::{CmdError, CmdResult, Ctx};
17use crate::envelope::Envelope;
18
19use taskfast_client::api::types::{
20 BidDetailStatus, BidRequest, RejectBidBody, RejectBidBodyReason,
21};
22use taskfast_client::map_api_error;
23use taskfast_client::TaskFastClient;
24
25#[derive(Debug, Subcommand)]
26pub enum Command {
27 List(ListArgs),
29 Create(CreateArgs),
31 Cancel(CancelArgs),
33 Accept(AcceptArgs),
35 Reject(RejectArgs),
37}
38
39#[derive(Debug, Parser)]
40pub struct ListArgs {
41 #[arg(long)]
43 pub cursor: Option<String>,
44
45 #[arg(long, default_value_t = 20)]
48 pub limit: i64,
49
50 #[arg(long)]
54 pub status: Option<BidStatusFilter>,
55}
56
57#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
62pub enum BidStatusFilter {
63 Pending,
64 Accepted,
65 Rejected,
66 Withdrawn,
67}
68
69impl BidStatusFilter {
70 fn matches(self, status: BidDetailStatus) -> bool {
71 matches!(
72 (self, status),
73 (Self::Pending, BidDetailStatus::Pending)
74 | (Self::Accepted, BidDetailStatus::Accepted)
75 | (Self::Rejected, BidDetailStatus::Rejected)
76 | (Self::Withdrawn, BidDetailStatus::Withdrawn)
77 )
78 }
79}
80
81#[derive(Debug, Parser)]
82pub struct CreateArgs {
83 pub task_id: String,
85
86 #[arg(long)]
89 pub price: String,
90
91 #[arg(long)]
93 pub pitch: Option<String>,
94}
95
96#[derive(Debug, Parser)]
97pub struct CancelArgs {
98 pub id: String,
100}
101
102#[derive(Debug, Args)]
103pub struct AcceptArgs {
104 pub id: String,
106}
107
108#[derive(Debug, Args)]
109pub struct RejectArgs {
110 pub id: String,
112 #[arg(long)]
114 pub reason: Option<String>,
115}
116
117pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
118 match cmd {
119 Command::List(args) => list(ctx, args).await,
120 Command::Create(args) => create(ctx, args).await,
121 Command::Cancel(args) => cancel(ctx, args).await,
122 Command::Accept(args) => accept(ctx, args).await,
123 Command::Reject(args) => reject(ctx, args).await,
124 }
125}
126
127async fn list(ctx: &Ctx, args: ListArgs) -> CmdResult {
128 let client = ctx.client()?;
129 let data = list_bids(&client, &args).await?;
130 Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
131}
132
133async fn list_bids(
134 client: &TaskFastClient,
135 args: &ListArgs,
136) -> Result<serde_json::Value, CmdError> {
137 let resp = match client
138 .inner()
139 .get_agent_bids(
140 args.cursor.as_deref(),
141 taskfast_client::page_limit(args.limit),
142 )
143 .await
144 {
145 Ok(v) => v.into_inner(),
146 Err(e) => return Err(map_api_error(e).await.into()),
147 };
148 let filter_applied = args.status.is_some();
155 let bids = match args.status {
156 Some(f) => resp
157 .data
158 .into_iter()
159 .filter(|b| b.status.is_some_and(|s| f.matches(s)))
160 .collect::<Vec<_>>(),
161 None => resp.data,
162 };
163 if filter_applied {
164 Ok(json!({
165 "bids": bids,
166 "meta": resp.meta,
167 "filtered_count": bids.len(),
168 }))
169 } else {
170 Ok(json!({
171 "bids": bids,
172 "meta": resp.meta,
173 }))
174 }
175}
176
177async fn create(ctx: &Ctx, args: CreateArgs) -> CmdResult {
178 let task_id = Uuid::parse_str(&args.task_id)
180 .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
181 if args.price.trim().is_empty() {
185 return Err(CmdError::Usage("--price must not be empty".into()));
186 }
187
188 if ctx.dry_run {
189 return Ok(Envelope::success(
190 ctx.environment,
191 ctx.dry_run,
192 json!({
193 "action": "would_create_bid",
194 "task_id": task_id.to_string(),
195 "price": args.price,
196 "pitch": args.pitch,
197 }),
198 ));
199 }
200
201 let client = ctx.client()?;
202 let body = BidRequest {
203 price: args.price.clone(),
204 pitch: args.pitch.clone(),
205 };
206 let bid = match client.inner().create_bid(&task_id, &body).await {
207 Ok(v) => v.into_inner(),
208 Err(e) => return Err(map_api_error(e).await.into()),
209 };
210 Ok(Envelope::success(
211 ctx.environment,
212 ctx.dry_run,
213 json!({ "bid": bid }),
214 ))
215}
216
217async fn cancel(ctx: &Ctx, args: CancelArgs) -> CmdResult {
218 let bid_id = Uuid::parse_str(&args.id)
219 .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
220
221 if ctx.dry_run {
222 return Ok(Envelope::success(
223 ctx.environment,
224 ctx.dry_run,
225 json!({
226 "action": "would_cancel_bid",
227 "bid_id": bid_id.to_string(),
228 }),
229 ));
230 }
231
232 let client = ctx.client()?;
233 let bid = match client.inner().withdraw_bid(&bid_id).await {
234 Ok(v) => v.into_inner(),
235 Err(e) => return Err(map_api_error(e).await.into()),
236 };
237 Ok(Envelope::success(
238 ctx.environment,
239 ctx.dry_run,
240 json!({ "bid": bid }),
241 ))
242}
243
244async fn accept(ctx: &Ctx, args: AcceptArgs) -> CmdResult {
245 let bid_id = Uuid::parse_str(&args.id)
246 .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
247
248 if ctx.dry_run {
249 return Ok(Envelope::success(
250 ctx.environment,
251 ctx.dry_run,
252 json!({
253 "action": "would_accept_bid",
254 "bid_id": bid_id.to_string(),
255 }),
256 ));
257 }
258
259 let client = ctx.client()?;
260 let resp = match client.inner().accept_bid(&bid_id).await {
261 Ok(v) => v.into_inner(),
262 Err(e) => return Err(map_api_error(e).await.into()),
263 };
264 Ok(Envelope::success(
265 ctx.environment,
266 ctx.dry_run,
267 json!({ "bid": resp }),
268 ))
269}
270
271async fn reject(ctx: &Ctx, args: RejectArgs) -> CmdResult {
272 let bid_id = Uuid::parse_str(&args.id)
273 .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
274
275 let reason_field = match args.reason.as_deref() {
278 Some(s) if s.trim().is_empty() => {
279 return Err(CmdError::Usage(
280 "--reason must not be empty when passed".into(),
281 ));
282 }
283 Some(s) => Some(
284 RejectBidBodyReason::try_from(s)
285 .map_err(|e| CmdError::Usage(format!("--reason invalid: {e}")))?,
286 ),
287 None => None,
288 };
289
290 if ctx.dry_run {
291 return Ok(Envelope::success(
292 ctx.environment,
293 ctx.dry_run,
294 json!({
295 "action": "would_reject_bid",
296 "bid_id": bid_id.to_string(),
297 "reason": args.reason,
298 }),
299 ));
300 }
301
302 let client = ctx.client()?;
303 let body = RejectBidBody {
304 reason: reason_field,
305 };
306 let resp = match client.inner().reject_bid(&bid_id, &body).await {
307 Ok(v) => v.into_inner(),
308 Err(e) => return Err(map_api_error(e).await.into()),
309 };
310 Ok(Envelope::success(
311 ctx.environment,
312 ctx.dry_run,
313 json!({ "bid": resp }),
314 ))
315}